-
# module BxBlockLogin
-
# class AccountAdapter
-
# include Wisper::Publisher
-
-
# def login_account(account_params)
-
# case account_params.type
-
# when 'sms_account'
-
# phone = Phonelib.parse(account_params.full_phone_number).sanitized
-
# account = AccountBlock::SmsAccount.find_by(
-
# full_phone_number: phone,
-
# activated: true)
-
# when 'email_account'
-
# email = account_params.email.downcase
-
-
# account = AccountBlock::EmailAccount
-
# .where('LOWER(email) = ?', email)
-
# .where(:activated => true)
-
# .first
-
# when 'social_account'
-
# account = AccountBlock::SocialAccount.find_by(
-
# email: account_params.email.downcase,
-
# unique_auth_id: account_params.unique_auth_id,
-
# activated: true)
-
# end
-
-
# unless account.present?
-
# broadcast(:account_not_found)
-
# return
-
# end
-
-
# if account.authenticate(account_params.password)
-
# token, refresh_token = generate_tokens(account.id)
-
# broadcast(:successful_login, account, token, refresh_token)
-
# else
-
# broadcast(:failed_login)
-
# end
-
# end
-
-
# def generate_tokens(account_id)
-
# [
-
# BuilderJsonWebToken.encode(account_id, 1.day.from_now, token_type: 'login'),
-
# BuilderJsonWebToken.encode(account_id, 1.year.from_now, token_type: 'refresh')
-
# ]
-
# end
-
# end
-
# end
-
-
1
module BxBlockLogin
-
1
class AccountAdapter
-
1
include Wisper::Publisher
-
-
1
def login_account(account_params)
-
3
case account_params.type
-
when 'sms_account'
-
phone = Phonelib.parse(account_params.full_phone_number).sanitized
-
account = AccountBlock::Account.find_by(
-
full_phone_number: phone,
-
activated: true)
-
when 'email_account'
-
3
if account_params.email
-
3
account = AccountBlock::Account.find_by(
-
email: account_params.email,
-
# full_phone_number: account_params.full_phone_number,
-
activated: true)
-
elsif account_params.full_phone_number
-
account = AccountBlock::Account.find_by(
-
# email: account_params.email,
-
full_phone_number: account_params.full_phone_number,
-
activated: true)
-
end
-
when 'social_account'
-
account = AccountBlock::SocialAccount.find_by(
-
email: account_params.email.downcase,
-
unique_auth_id: account_params.unique_auth_id,
-
activated: true)
-
end
-
-
3
unless account.present?
-
1
broadcast(:account_not_found)
-
1
return
-
end
-
-
# if account.authenticate(account_params.password)
-
2
token = BuilderJsonWebToken.encode(account.id)
-
2
broadcast(:successful_login, account, token)
-
# else
-
# broadcast(:failed_login)
-
# end
-
end
-
end
-
end
-
1
ActiveAdmin.register BxBlockAdmin::AboutUs, as: 'About Us' do
-
1
permit_params :content, :description
-
-
1
index do
-
1
selectable_column
-
1
id_column
-
1
column :about_us do|about_us|
-
1
truncate(about_us.content, omision: "...", length: 50)
-
end
-
1
column :description
-
1
actions
-
end
-
-
1
form do |f|
-
1
inputs 'About Us'do
-
1
f.input :content, as: :quill_editor, input_html: { data: { options: { modules: { }, placeholder: 'Insert Images', theme: 'snow' } } }
-
1
f.input :description, as: :quill_editor, input_html: { data: { options: { modules: { }, placeholder: 'Insert Description...', theme: 'snow' } } }
-
end
-
1
f.actions
-
end
-
-
1
show do |about_us|
-
1
attributes_table do
-
1
div :class => "ql-editor" do
-
1
about_us.content.html_safe
-
end
-
1
row :description
-
end
-
end
-
end
-
1
ActiveAdmin.register AdminUser do
-
1
permit_params :email, :password, :password_confirmation
-
-
1
index do
-
selectable_column
-
id_column
-
column :email
-
column :current_sign_in_at
-
column :sign_in_count
-
column :created_at
-
actions
-
end
-
-
1
filter :email
-
1
filter :current_sign_in_at
-
1
filter :sign_in_count
-
1
filter :created_at
-
-
1
form do |f|
-
f.inputs do
-
f.input :email
-
f.input :password
-
f.input :password_confirmation
-
end
-
f.actions
-
end
-
end
-
-
1
module AdminUsers
-
end
-
1
ActiveAdmin.register BxBlockBook::AdditionalPricePerPage, as: "Price Per Page" do
-
1
permit_params :additional_price
-
end
-
1
ActiveAdmin.register BxBlockBook::BookColor, as: "Book Colors" do
-
1
permit_params :book_color, :title_color, :logo_color
-
-
1
controller do
-
1
def action_methods
-
9
if BxBlockBook::BookColor.all&.count < 3
-
9
super
-
else
-
super - ['new', 'create']
-
end
-
end
-
-
1
def index
-
1
index! do |format|
-
1
format.html
-
1
format.pdf {
-
@book = BxBlockBook::BookColor.all
-
pdf_html = ActionController::Base.new.render_to_string(template: 'all_book_color', locals: { books: @book})
-
pdf = WickedPdf.new.pdf_from_string(pdf_html)
-
send_data pdf, filename: 'book_color.pdf'
-
}
-
end
-
end
-
end
-
-
1
form do |f|
-
1
f.semantic_errors *f.object.errors.keys
-
1
f.inputs do
-
1
li do
-
1
f.input :book_color, as: :color
-
1
f.input :logo_color, as: :color
-
1
f.input :title_color, as: :color
-
end
-
end
-
-
1
f.actions
-
end
-
end
-
1
ActiveAdmin.register BxBlockBook::Book, as: 'Books' do
-
1
permit_params :year, :month, :flag, :account_id, :book_color, :title_layout, :cover_type, :paper_type, :book_title, :month_range, :month_year, :images, :cover_image
-
-
1
remove_filter :images_attachments
-
1
remove_filter :images_blobs
-
1
remove_filter :cover_image_attachment
-
1
remove_filter :cover_image_blob
-
-
1
controller do
-
1
def index
-
# index! do |format|
-
# format.html
-
# format.pdf {
-
# @book = BxBlockBook::Book.all
-
# pdf_html = ActionController::Base.new.render_to_string(template: 'all_book', locals: { books: @book})
-
# pdf = WickedPdf.new.pdf_from_string(pdf_html)
-
# send_data pdf, filename: 'book.pdf'
-
-
# }
-
# end
-
-
super
-
end
-
end
-
-
1
action_item :download_image, only: :show do
-
link_to 'Download images in zip', bulk_download_zip_bx_block_book_book_path(resource.id)
-
end
-
-
1
index do
-
selectable_column
-
id_column
-
column :year
-
column :month
-
column :account_id
-
column :book_color
-
column :title_layout
-
column :cover_type
-
column :paper_type
-
column :book_title
-
column :month_range
-
column :month_year
-
# column :images
-
column :shareable_identity
-
actions default: false do |book|
-
link_to 'Download Book', download_pdf_bx_block_book_book_path(book.id, format: :pdf),
-
class: 'view_link member_link'
-
end
-
end
-
-
1
show do |book|
-
div do
-
if book.book_title.present?
-
h3 book.book_title
-
else
-
h3 book.year
-
h3 book.month
-
end
-
-
div :class => "col-xs-4" do
-
if book.cover_image.present?
-
image_tag(url_for(book.cover_image),width:500,height:500)
-
end
-
end
-
-
div :class => "col-xs-4" do
-
if book.cover_image.present?
-
@host = Rails.env.development? ? 'http://localhost:3000' : ENV['HOST_URL']
-
link_to "Download this image", @host + rails_blob_path(book.cover_image, only_url: true).html_safe, disposition: 'attachment', download: true
-
end
-
end
-
-
book&.images&.order(:index).each do |image|
-
td do
-
div :class => "col-xs-4" do
-
image_tag(url_for(image),width:500,height:500)
-
end
-
end
-
end
-
end
-
end
-
end
-
1
ActiveAdmin.register BxBlockBook::DeliveryCharge, as: "Delivery Charge" do
-
1
permit_params :charge
-
end
-
1
ActiveAdmin.register BxBlockBook::ImageLimit do
-
-
# See permitted parameters documentation:
-
# https://github.com/activeadmin/activeadmin/blob/master/docs/2-resource-customization.md#setting-up-strong-parameters
-
#
-
# Uncomment all parameters which should be permitted for assignment
-
#
-
1
permit_params :min_images, :max_images, :img_resolution
-
#
-
# or
-
#
-
# permit_params do
-
# permitted = [:min_images, :max_images, :img_resolution]
-
# permitted << :other if params[:action] == 'create' && current_user.admin?
-
# permitted
-
# end
-
-
end
-
1
ActiveAdmin.register BxBlockBook::Price, as: "Prices" do
-
1
permit_params :cover_type, :price, :min_limit, :max_limit, :book_size
-
-
1
controller do
-
1
def action_methods
-
if BxBlockBook::Price.all&.count < 2
-
super
-
else
-
super - ['new', 'create']
-
end
-
end
-
end
-
end
-
1
ActiveAdmin.register BxBlockDiscountsoffers::Offer, as: "Offers" do
-
1
permit_params :phone_number, :email, :full_phone_number, :title, :description, :code, :min_cart_value, :discount, :discount_type, :valid_from, :valid_to, :active, :max_limit, :valid_for, :coupon_type, :max_capping_limit
-
-
1
form do |f|
-
1
f.semantic_errors *f.object.errors.keys
-
1
f.inputs do
-
1
f.input :coupon_type, as: :select
-
1
f.input :title
-
-
1
div class: "referral1-div" do
-
1
f.input :description
-
end
-
-
1
div class: "referral2-div" do
-
1
f.input :valid_for, as: :select
-
end
-
-
1
div class: "referral3-div" do
-
1
f.input :code
-
end
-
-
1
div class: "specfic_user-div" do
-
3
f.input :phone_number, as: :tags, collection: (AccountBlock::Account.all.map {|entity| entity.full_phone_number})
-
3
f.input :email, as: :tags, collection: (AccountBlock::Account.all.map {|entity| entity.email})
-
end
-
1
f.input :min_cart_value
-
1
f.input :discount
-
1
f.input :discount_type, as: :select, collection: ['flat', 'percentage']
-
1
div class: "cap-div" do
-
1
f.input :max_capping_limit
-
end
-
1
f.input :valid_from, as: :date_picker#, hint: 'Please add time in GMT/UTC'
-
1
f.input :valid_to, as: :date_picker#, hint: 'Please add time in GMT/UTC'
-
1
f.input :active
-
1
f.input :max_limit
-
1
f.input :combine_with_other_offer
-
1
div class: "discount-div" do
-
1
f.input :extra_discount
-
1
f.input :discount_type, as: :select, collection: ['flat', 'percentage']
-
end
-
end
-
1
f.actions
-
end
-
end
-
1
ActiveAdmin.register BxBlockHelpCentre::QuestionAnswer, as: "Question Answers" do
-
1
permit_params :question, :answer
-
end
-
1
ActiveAdmin.register BxBlockOrderManagement::OrderTransaction, as: "Transactions" do
-
-
# See permitted parameters documentation:
-
# https://github.com/activeadmin/activeadmin/blob/master/docs/2-resource-customization.md#setting-up-strong-parameters
-
#
-
# Uncomment all parameters which should be permitted for assignment
-
#
-
1
permit_params :account_id, :order_id, :charge_id, :amount, :currency, :charge_status, :razorpay_order_id, :razorpay_payment_id, :razorpay_signature, :status
-
#
-
# or
-
#
-
# permit_params do
-
# permitted = [:account_id, :order_id, :charge_id, :amount, :currency, :charge_status, :razorpay_order_id, :razorpay_payment_id, :razorpay_signature, :status]
-
# permitted << :other if params[:action] == 'create' && current_user.admin?
-
# permitted
-
# end
-
-
1
index do
-
selectable_column
-
id_column
-
column :account_id
-
column :order_id
-
column :amount
-
column :razorpay_order_id
-
column :razorpay_payment_id
-
column :razorpay_signature
-
column :status
-
actions
-
end
-
end
-
1
ActiveAdmin.register BxBlockStories::Blog, as: 'Blogs' do
-
1
require 'streamio-ffmpeg'
-
-
# See permitted parameters documentation:
-
# https://github.com/activeadmin/activeadmin/blob/master/docs/2-resource-customization.md#setting-up-strong-parameters
-
#
-
# Uncomment all parameters which should be permitted for assignment
-
#
-
1
permit_params :description, :title, :status, :blog_file
-
-
1
form do |f|
-
f.inputs do
-
hints = "<p style='padding-left:372px; font-size: 12px; margin-top:-15px;'><span>Max width of an image should be 991 px</span></p><p style='padding-left:372px; font-size: 12px;margin-top:-12px;'><span>Supported format for Images - .JPEG , .PNG, .BMP , .WEBP</span></p><p style='padding-left:372px; padding-bottom: 15px; font-size: 12px;margin-top:-10px;'><span>Supported format for Video - .MP4, .MOV, .WEBM, .MKV</span></p>".html_safe
-
-
f.input :blog_file, as: :file, hint: f.object.blog_file.attached? ? (BxBlockStories::Blog::BLOG_CONTENT_TYPE.include?(f.object.blog_file&.content_type) ? hints + image_tag(url_for(f.object.blog_file), size: "250x200", style: 'margin-left:372px;') : hints + video_tag(url_for(f.object.blog_file), height: "150px", controls: true, style: 'padding-left:372px;')) : hints
-
f.input :title
-
f.input :description
-
f.input :status
-
end
-
f.actions do
-
f.action :submit
-
f.cancel_link(action: 'index')
-
end
-
end
-
-
1
show do |blog|
-
attributes_table do
-
row :id
-
row :blog_file do |blog|
-
div :class => "col-xs-4" do
-
if blog.blog_file.attached?
-
if BxBlockStories::Blog::BLOG_CONTENT_TYPE.include?(blog.blog_file&.content_type)
-
image_tag(url_for(blog.blog_file))
-
else
-
video_tag(url_for(blog.blog_file), controls: true)
-
end
-
end
-
end
-
end
-
row :title
-
row :description
-
row :url
-
row :status
-
end
-
end
-
end
-
1
ActiveAdmin.register BxBlockStories::Story, as: 'Stories' do
-
1
require 'streamio-ffmpeg'
-
-
# See permitted parameters documentation:
-
# https://github.com/activeadmin/activeadmin/blob/master/docs/2-resource-customization.md#setting-up-strong-parameters
-
#
-
# Uncomment all parameters which should be permitted for assignment
-
#
-
1
permit_params :description, :valid_till, :story_file, :active, :story_type, :title, :link
-
-
# Filterable attributes on the index screen
-
1
filter :valid_till
-
-
1
index :download_links => false do
-
1
selectable_column
-
1
id_column
-
1
column :story_file do |story|
-
1
div :class => "story_img" do
-
1
if story.story_file.attached?
-
if BxBlockStories::Story::STORY_CONTENT_TYPE.include?(story.story_file&.content_type)
-
image_tag(url_for(story.story_file), size: "150x120")
-
else
-
video_tag(url_for(story.story_file), size: "150x120", controls: true)
-
end
-
end
-
end
-
end
-
1
column :valid_till
-
1
column :story_type
-
1
column :active
-
1
actions
-
end
-
-
1
show do |story|
-
1
attributes_table do
-
1
row :id
-
1
row :story_file do |story|
-
1
div :class => "col-xs-4" do
-
1
if story.story_file.attached?
-
if BxBlockStories::Story::STORY_CONTENT_TYPE.include?(story.story_file&.content_type)
-
image_tag(url_for(story.story_file), size: "150x120")
-
else
-
video_tag(url_for(story.story_file), size: "150x120", controls: true)
-
end
-
end
-
end
-
end
-
1
row :story_type
-
1
row :description
-
1
row :valid_till
-
1
row :active
-
end
-
end
-
-
1
form do |f|
-
1
f.inputs do
-
1
f.input :story_type
-
1
hints = "<p style='padding-left:372px; font-size: 12px; margin-top:-15px;'><span>Max width of an image should be 991 px</span></p><p style='padding-left:372px; font-size: 12px;margin-top:-12px;'><span>Supported format for Images - .JPEG , .PNG, .BMP , .WEBP</span></p><p style='padding-left:372px; padding-bottom: 15px; font-size: 12px;margin-top:-10px;'><span>Supported format for Video - .MP4, .MOV, .WEBM, .MKV</span></p>".html_safe
-
1
div class: "blog-div" do
-
1
f.input :title
-
end
-
1
f.input :story_file, as: :file, hint: f.object.story_file.attached? ? (BxBlockStories::Story::STORY_CONTENT_TYPE.include?(f.object.story_file&.content_type) ? hints + image_tag(url_for(f.object.story_file), height: "150px", style: 'padding-left:372px;') : hints + video_tag(url_for(f.object.story_file), height: "150px", controls: true, style: 'padding-left:372px;')) : hints
-
1
f.input :description
-
1
div class: "blog-div" do
-
1
f.input :link
-
end
-
1
f.input :valid_till, as: :datetime_picker, hint: 'Please add time in GMT/UTC'
-
1
f.input :active
-
end
-
1
f.actions do
-
1
f.action :submit
-
1
f.cancel_link(action: 'index')
-
end
-
end
-
-
1
controller do
-
1
def create
-
if params['bx_block_stories_story']['story_file'].present? && params['bx_block_stories_story']['valid_till'].present?
-
file_path = params['bx_block_stories_story']['story_file'].tempfile.path
-
movie = FFMPEG::Movie.new(file_path)
-
if movie.valid?
-
if movie.duration.to_i > 60.seconds
-
redirect_to new_admin_story_path
-
flash[:alert] = 'Please upload a video less then 1 minute'
-
elsif movie.width > movie.height && (!movie.path.include?('.mp4') && !movie.path.include?('.mov') && !movie.path.include?('.webm') && !movie.path.include?('.mkv'))
-
redirect_to new_admin_story_path
-
flash[:alert] = 'Please upload a portait image'
-
else
-
super
-
end
-
end
-
else
-
super
-
end
-
end
-
-
1
def update
-
if params['bx_block_stories_story']['story_file'].present? && params['bx_block_stories_story']['valid_till'].present?
-
file_path = params['bx_block_stories_story']['story_file'].tempfile.path
-
movie = FFMPEG::Movie.new(file_path)
-
if movie.valid?
-
if movie.duration.to_i > 60.seconds
-
redirect_to edit_admin_story_path
-
flash[:alert] = 'Please upload a video less then 1 minute'
-
elsif movie.width > movie.height && (!movie.path.include?('.mp4') && !movie.path.include?('.mov') && !movie.path.include?('.webm') && !movie.path.include?('.mkv'))
-
redirect_to edit_admin_story_path
-
flash[:alert] = 'Please upload a portait image'
-
else
-
super
-
end
-
end
-
else
-
super
-
end
-
end
-
end
-
end
-
1
ActiveAdmin.register BxBlockContentManagement::CustomEmail, as: "CustomEmails" do
-
-
1
permit_params :description, :title, :email_type, :address, :email, :timing_of_service, :phone_no, :image1, :image2, :image3, :image4, :image5, :image6, :image7, :image8
-
-
1
form do |f|
-
1
f.inputs do
-
1
f.input :email_type
-
# f.input :valid_for
-
1
f.input :image1, as: :file
-
1
f.input :image2, as: :file
-
1
f.input :image3, as: :file
-
1
f.input :image4, as: :file
-
1
f.input :image5, as: :file
-
1
f.input :image6, as: :file
-
1
div class: "type-div" do
-
1
f.input :image7, as: :file
-
1
f.input :image8, as: :file
-
end
-
1
f.input :email
-
1
f.input :timing_of_service
-
1
f.input :phone_no
-
1
f.input :title, as: :quill_editor
-
1
f.input :description, as: :quill_editor
-
1
f.input :address, as: :quill_editor
-
-
end
-
1
f.actions
-
end
-
-
1
show do |custom_emails|
-
1
attributes_table do
-
1
row :email_type
-
# row :valid_for
-
1
row :email
-
1
row :phone_no
-
1
row :timing_of_service
-
1
row :title do |custom_emails|
-
1
custom_emails&.title&.html_safe
-
end
-
1
row :description do |custom_emails|
-
1
custom_emails&.description&.html_safe
-
end
-
1
row :address do |custom_emails|
-
1
custom_emails&.address&.html_safe
-
end
-
1
row :image1 do |custom_emails|
-
1
div do
-
1
image_tag(url_for(custom_emails.image1), size: "100x100") if custom_emails.image1.attached?
-
end
-
end
-
1
row :image2 do |custom_emails|
-
1
div do
-
1
image_tag(url_for(custom_emails.image2), size: "500x500") if custom_emails.image2.attached?
-
end
-
end
-
1
row :image3 do |custom_emails|
-
1
div do
-
1
image_tag(url_for(custom_emails.image3), size: "500x500") if custom_emails.image3.attached?
-
end
-
end
-
1
row :image4 do |custom_emails|
-
1
div do
-
1
image_tag(url_for(custom_emails.image4), size: "500x500") if custom_emails.image4.attached?
-
end
-
end
-
1
row :image5 do |custom_emails|
-
1
div do
-
1
image_tag(url_for(custom_emails.image5), size: "500x500") if custom_emails.image5.attached?
-
end
-
end
-
1
row :image6 do |custom_emails|
-
1
div do
-
1
image_tag(url_for(custom_emails.image6), size: "500x500") if custom_emails.image6.attached?
-
end
-
end
-
1
row :image7 do |custom_emails|
-
1
div do
-
1
image_tag(url_for(custom_emails.image7), size: "500x500") if custom_emails.image7.attached?
-
end
-
end
-
1
row :image8 do |custom_emails|
-
1
div do
-
1
image_tag(url_for(custom_emails.image8), size: "500x500") if custom_emails.image8.attached?
-
end
-
end
-
end
-
end
-
-
1
index do
-
1
selectable_column
-
1
column :email_type
-
1
column :email
-
1
column :phone_no
-
1
column :timing_of_service
-
1
column :title do |custom_emails|
-
2
custom_emails&.title&.html_safe
-
end
-
1
column :description do |custom_emails|
-
2
custom_emails&.description&.html_safe
-
end
-
1
column :address do |custom_emails|
-
2
custom_emails&.address&.html_safe
-
end
-
1
column :image1 do |custom_emails|
-
2
div do
-
2
image_tag(url_for(custom_emails.image1), size: "100x100") if custom_emails.image1.attached?
-
end
-
end
-
1
column :image2 do |custom_emails|
-
2
div do
-
2
image_tag(url_for(custom_emails.image2), size: "100x100") if custom_emails.image2.attached?
-
end
-
end
-
1
column :image3 do |custom_emails|
-
2
div do
-
2
image_tag(url_for(custom_emails.image3), size: "500x500") if custom_emails.image3.attached?
-
end
-
end
-
1
column :image4 do |custom_emails|
-
2
div do
-
2
image_tag(url_for(custom_emails.image4), size: "100x100") if custom_emails.image4.attached?
-
end
-
end
-
1
column :image5 do |custom_emails|
-
2
div do
-
2
image_tag(url_for(custom_emails.image5), size: "300x300") if custom_emails.image5.attached?
-
end
-
end
-
1
column :image6 do |custom_emails|
-
2
div do
-
2
image_tag(url_for(custom_emails.image6), size: "300x300") if custom_emails.image6.attached?
-
end
-
end
-
1
column :image7 do |custom_emails|
-
2
div do
-
2
image_tag(url_for(custom_emails.image7), size: "300x300") if custom_emails.image7.attached?
-
end
-
end
-
1
column :image8 do |custom_emails|
-
2
div do
-
2
image_tag(url_for(custom_emails.image8), size: "300x300") if custom_emails.image8.attached?
-
end
-
end
-
1
actions
-
end
-
end
-
1
ActiveAdmin.register_page "Dashboard" do
-
18
menu priority: 1, label: proc { I18n.t("active_admin.dashboard") }
-
-
1
content title: proc { I18n.t("active_admin.dashboard") } do
-
div class: "blank_slate_container", id: "dashboard_default_message" do
-
span class: "blank_slate" do
-
span I18n.t("active_admin.dashboard_welcome.welcome")
-
small I18n.t("active_admin.dashboard_welcome.call_to_action")
-
end
-
end
-
-
# Here is an example of a simple dashboard with columns and panels.
-
#
-
# columns do
-
# column do
-
# panel "Recent Posts" do
-
# ul do
-
# Post.recent(5).map do |post|
-
# li link_to(post.title, admin_post_path(post))
-
# end
-
# end
-
# end
-
# end
-
-
# column do
-
# panel "Info" do
-
# para "Welcome to ActiveAdmin."
-
# end
-
# end
-
# end
-
end # content
-
end
-
-
1
module Dashboard
-
end
-
1
ActiveAdmin.register AccountBlock::DashboardMediaFile, as: 'Dashboard Media Files' do
-
1
permit_params :name, :priority, :media_file
-
-
1
index do
-
selectable_column
-
id_column
-
column :name
-
column :priority
-
actions
-
end
-
-
1
form do |f|
-
inputs 'Dashboard Media Files'do
-
f.input :name
-
f.input :priority
-
hints = "<p style='padding-left:372px; font-size: 12px;margin-top:-12px;'><span>Supported format for Images - .JPEG , .PNG, .BMP , .WEBP</span></p><p style='padding-left:372px; padding-bottom: 15px; font-size: 12px;margin-top:-10px;'><span>Supported format for Video - .MP4, .MOV ,.WEBM , .MKV</span></p>".html_safe
-
f.input :media_file, as: :file, :hint => object.media_file.present? ? hints + image_tag(url_for(object.media_file), style: 'width: 200px; margin-left: 372px;') : hints
-
end
-
actions
-
end
-
-
1
show do
-
attributes_table do
-
row :name
-
row :priority
-
row :media_file do |dashboard|
-
ul do
-
span do
-
if dashboard.media_file.attached?
-
file_formate = dashboard.media_file.content_type.split("/").first
-
if file_formate == "video"
-
if Rails.env.development?
-
video_tag url_for(dashboard.media_file), autoplay: false, controls: true
-
# image_tag url_for(dashboard.media_file), style: "max-width: 300px; max-height: 400px;" ,class: 'img-wrap'
-
else
-
video_tag dashboard.media_file.service_url, autoplay: false, controls: true
-
# image_tag dashboard.media_file.service_url, style: "max-width: 300px; max-height: 400px;" ,class: 'img-wrap' if dashboard.media_file.attached?
-
end
-
elsif file_formate == "image"
-
if Rails.env.development?
-
image_tag url_for(dashboard.media_file), style: "max-width: 300px; max-height: 400px;" ,class: 'img-wrap'
-
else
-
image_tag dashboard.media_file.service_url, style: "max-width: 300px; max-height: 400px;" ,class: 'img-wrap' if dashboard.media_file.attached?
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
end
-
1
ActiveAdmin.register AccountBlock::DraftMailTimer, as: 'Draft Mail Timer' do
-
1
permit_params :first_mail_in_minuts, :second_mail_in_days
-
-
# actions :index, :show, :edit, :update
-
end
-
1
ActiveAdmin.register BxBlockOrderManagement::Order, as: "Orders" do
-
1
permit_params :account_id, :sub_total, :amount, :no_of_pages, :book_size, :book_title, :book_color, :cover_type, :paper_type, :book_id, :placed_at
-
1
actions :all, :except => [:edit, :new]
-
-
1
controller do
-
1
def index
-
-
index! do |format|
-
format.html
-
format.pdf {
-
@orders = BxBlockOrderManagement::Order.all
-
pdf_html = ActionController::Base.new.render_to_string(template: 'all_order', locals: { orders: @orders})
-
pdf = WickedPdf.new.pdf_from_string(pdf_html)
-
send_data pdf, filename: 'file.pdf'
-
}
-
end
-
end
-
end
-
-
1
action_item :download_image, only: :show do
-
link_to 'Download images in zip', bulk_download_zip_bx_block_book_book_path(resource.book_id, order_id: resource.id)
-
end
-
-
1
index do
-
selectable_column
-
id_column
-
column :account_id
-
column :sub_total
-
column :amount
-
column :no_of_pages
-
column :book_size
-
column :book_title
-
column :book_color
-
column :cover_type
-
column :paper_type
-
column :book_id
-
column :status
-
column :payment_status
-
# column :placed_at
-
column :placed_at, :sortable => :placed_at do |obj|
-
obj.placed_at.localtime.in_time_zone("Asia/Kolkata") if obj.placed_at.present?
-
end
-
column "Size" do |order|
-
total = 0
-
book = BxBlockBook::Book.find_by(id: order.book_id)
-
if book&.images.present?
-
book&.images.each do |image|
-
total += image.blob.byte_size
-
end
-
end
-
total
-
end
-
column "email" do |order|
-
order.account&.email
-
end
-
column "full_phone_number" do |order|
-
order.account&.full_phone_number
-
end
-
actions default: false do |order|
-
link_to 'Download Order', download_order_bx_block_book_book_path(order.id, format: :pdf),
-
class: 'view_link member_link'
-
end
-
end
-
-
1
show do
-
attributes_table do
-
row "Order Id" do |order|
-
order&.id
-
end
-
row :order_number
-
row "Order Date" do |order|
-
# order&.created_at
-
order&.created_at.localtime.in_time_zone("Asia/Kolkata")
-
end
-
row :account_id
-
row :status
-
row :applied_discount
-
row :sub_total
-
row :amount
-
row :razorpay_order_id
-
row :ship_rocket_order_id
-
row :ship_rocket_status
-
row :ship_rocket_shipment_id
-
-
panel "Book Details" do
-
@book = BxBlockBook::Book.find_by(id: resource.book_id)
-
table_for @book do
-
column :id
-
column "book_size" do |book|
-
resource&.book_size
-
end
-
column "book_title" do |book|
-
book&.book_title
-
end
-
column "book_color" do |book|
-
book&.book_color
-
end
-
column "cover_type" do |book|
-
book&.cover_type
-
end
-
column "no_of_pages" do |book|
-
resource&.no_of_pages
-
end
-
column "book_url" do |book|
-
link_to resource&.book_url, resource&.book_url, target: :_blank
-
end
-
end
-
end
-
-
panel "Customer Details" do
-
table_for resource.address do
-
column :id
-
column "full_name" do |q|
-
q&.full_name
-
end
-
column "pincode" do |q|
-
q&.pincode
-
end
-
column "city" do |q|
-
q&.city
-
end
-
column "address" do |q|
-
q&.address
-
end
-
column "state" do |q|
-
q&.state
-
end
-
column "email" do |q|
-
q&.email_address || resource.account&.email
-
end
-
column "phone_number" do |q|
-
q&.phone_number || resource.account&.full_phone_number
-
end
-
end
-
end
-
end
-
end
-
-
1
action_item :complete_order, only: :show do
-
link_to 'Complete Order', complete_admin_order_path(resource), method: :put if resource.status != 'delivered'
-
end
-
-
1
member_action :complete, method: :put do
-
resource.update(status: "delivered")
-
redirect_to resource_path(resource), notice: "Order completed!"
-
end
-
end
-
-
-
-
1
ActiveAdmin.register BxBlockAdmin::PrivacyPolicy, as: 'Privacy Policy' do
-
1
permit_params :content
-
-
1
index do
-
selectable_column
-
id_column
-
column :privacy_policy do |privacy_policy|
-
truncate(privacy_policy.content, omision: "...", length: 50)
-
end
-
actions
-
end
-
-
1
form do |f|
-
f.semantic_errors *f.object.errors.keys
-
f.inputs do
-
li do
-
f.input :content, as: :quill_editor, input_html: { data: { options: { modules: { }, placeholder: 'Type something...', theme: 'snow' } } }
-
end
-
end
-
-
f.actions
-
end
-
-
1
show do |privacy_policy|
-
div :class => "ql-editor" do
-
privacy_policy.content.html_safe
-
end
-
end
-
end
-
-
1
ActiveAdmin.register BxBlockReferrals::ReferralLimitSetting, as: 'Referral Limit Setting' do
-
1
permit_params :max_order_refers, :active
-
# actions :all, :except => [:new]
-
1
form do |f|
-
f.input :max_order_refers
-
f.input :active
-
f.actions
-
end
-
-
end
-
1
ActiveAdmin.register BxBlockAdmin::ReturnAndRefundPolicy, as: 'Return And Refund Policy' do
-
1
permit_params :content
-
-
1
index do
-
selectable_column
-
id_column
-
column :rnr_policy do |rnr_policy|
-
truncate(rnr_policy.content, omision: "...", length: 50)
-
end
-
actions
-
end
-
-
1
form do |f|
-
f.semantic_errors *f.object.errors.keys
-
f.inputs do
-
f.input :content, as: :quill_editor, input_html: { data: { options: { modules: { }, placeholder: 'Type something...', theme: 'snow' } } }
-
end
-
-
f.actions
-
end
-
-
1
show do |rnr_policy|
-
div :class => "ql-editor" do
-
rnr_policy.content.html_safe
-
end
-
end
-
end
-
1
ActiveAdmin.register BxBlockCustomUserSubs::Subscription, as: 'subscription' do
-
1
require 'streamio-ffmpeg'
-
-
1
permit_params :name, :details, :active, :book_original_price, :no_of_books, :gift_included, :valid_up_to, :total_amount, :subscription_package_amount
-
-
1
index do
-
1
selectable_column
-
1
id_column
-
1
column :name
-
1
column :details
-
1
column :book_original_price
-
1
column :no_of_books
-
1
column :gift_included
-
1
column :valid_up_to
-
1
column :total_amount
-
1
column :subscription_package_amount
-
1
column :active
-
1
actions
-
end
-
end
-
1
ActiveAdmin.register BxBlockAdmin::TermsAndCondition, as: 'Terms and Condition' do
-
1
permit_params :content
-
-
1
index do
-
selectable_column
-
id_column
-
column :tnc do |tnc|
-
truncate(tnc.content, omision: "...", length: 50)
-
end
-
actions
-
end
-
-
1
form do |f|
-
f.semantic_errors *f.object.errors.keys
-
f.inputs do
-
li do
-
f.input :content, as: :quill_editor, input_html: { data: { options: { modules: { }, placeholder: 'Type something...', theme: 'snow' } } }
-
end
-
end
-
-
f.actions
-
end
-
-
1
show do |tnc|
-
div :class => "ql-editor" do
-
tnc.content.html_safe
-
end
-
end
-
end
-
1
ActiveAdmin.register BxBlockDiscountsoffers::UserOffer, as: "User Offers" do
-
1
permit_params :account_id, :offer_id, :use_count, :code, :applied, :coupon_type
-
-
1
index do
-
1
selectable_column
-
1
id_column
-
1
column :account do |resource|
-
1
resource.account_id if resource.account_id.present?
-
# link_to("#{resource.account&.full_name}", admin_user_path(resource.account)) if resource.account
-
end
-
1
column :offer
-
1
column :code
-
1
column :applied
-
1
column :use_count
-
1
column :created_at
-
1
column :updated_at
-
1
column :coupon_type
-
1
actions
-
end
-
end
-
1
ActiveAdmin.register AccountBlock::Account, as: "Users" do
-
1
permit_params :first_name, :last_name, :full_phone_number
-
-
1
index do
-
1
selectable_column
-
1
id_column
-
1
column :email
-
1
column :created_at
-
1
column :updated_at
-
1
column :activated
-
1
actions
-
end
-
-
1
show do
-
1
attributes_table do
-
1
row :full_name
-
1
row :provider
-
1
row :google_token
-
1
row :accounts
-
1
row :shared_link
-
1
row :email
-
1
row :activated
-
1
row :unique_auth_id
-
1
row :email_verified
-
1
row :phone_verified
-
1
row :full_phone_number
-
1
row :created_at
-
1
row :updated_at
-
1
row :type
-
end
-
end
-
-
1
form do |f|
-
1
f.inputs do
-
1
f.input :activated
-
1
f.input :full_name
-
1
f.actions
-
end
-
end
-
-
1
controller do
-
1
def destroy
-
sms_otps = AccountBlock::SmsOtp.where(full_phone_number: resource.full_phone_number)
-
email_otps = AccountBlock::EmailOtp.where(email: resource.email)
-
email_otps.destroy_all
-
sms_otps.destroy_all
-
super
-
end
-
end
-
end
-
module BxBlockCoupons
-
module CouponApplicabilityCommand
-
extend self
-
-
def check(account_id, params)
-
validator = BxBlockCoupons::CouponApplicabilityValidator.new(
-
account_id, params['name'], params['order_amount']
-
)
-
return [:unprocessable_entity, validator.errors.full_messages] unless validator.valid?
-
validator = validator.coupon
-
# coupon = find_coupon params['name']
-
discount_price = discount_amount(validator, params['order_amount'])
-
return [:coupon_applied, discount_price, validator.id]
-
end
-
-
private
-
-
def find_coupon name
-
coupon = BxBlockCoupons::Coupon.find_by_name(name)
-
return errors.add(:base, 'Invalid coupon') unless coupon.present?
-
end
-
-
def discount_amount coupon, order_amount
-
discount = ((order_amount.to_i * coupon.discount.to_i) / 100) if coupon.coupon_type == 'up_to'
-
discount = (coupon.max_discount) if coupon.coupon_type == 'flat'
-
end
-
end
-
end
-
module BxBlockProfile
-
module ChangePasswordCommand
-
extend self
-
-
def execute(account_id, password, new_password)
-
validator = ChangePasswordValidator
-
.new(account_id, password, new_password)
-
-
account = validator.account
-
-
unless validator.valid?
-
return [:unprocessable_entity, validator.errors.full_messages]
-
end
-
return [:created, account] if update_password(account, new_password)
-
[:unprocessable_entity, ['Password could not be saved']]
-
end
-
-
private
-
-
def update_password(account, new_password)
-
account.update :password => new_password
-
end
-
end
-
end
-
module BxBlockProfile
-
module UpdateAccountCommand
-
extend self
-
-
def execute(account_id, params)
-
validator = UpdateAccountValidator.new(account_id, params)
-
-
unless validator.valid?
-
return [:unprocessable_entity, validator.errors.full_messages]
-
end
-
-
account = validator.account
-
attrs = validator.attributes
-
-
return [:ok, account.reload] if account.update(attrs)
-
-
[:unprocessable_entity, ['Profile could not be saved']]
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
1
module BuilderJsonWebToken
-
1
module JsonWebTokenValidation
-
ERROR_CLASSES = [
-
1
JWT::DecodeError,
-
JWT::ExpiredSignature,
-
].freeze
-
-
1
private
-
-
1
def validate_json_web_token
-
50
token = request.headers[:token] || params[:token]
-
-
begin
-
50
@token = JsonWebToken.decode(token)
-
1
rescue *ERROR_CLASSES => exception
-
1
handle_exception exception
-
end
-
end
-
-
1
def handle_exception(exception)
-
# order matters here
-
# JWT::ExpiredSignature appears to be a subclass of JWT::DecodeError
-
1
case exception
-
when JWT::ExpiredSignature
-
return render json: { errors: [token: 'Token has Expired'] },
-
status: :unauthorized
-
when JWT::DecodeError
-
1
return render json: { errors: [token: 'Invalid token'] },
-
status: :bad_request
-
end
-
end
-
end
-
end
-
module BxBlockAttachment
-
module PatchAccountBlockAssociations
-
extend ActiveSupport::Concern
-
-
included do
-
has_many :attachments, class_name: 'BxBlockAttachment::Attachment', dependent: :destroy
-
end
-
-
end
-
end
-
module BxBlockBulkUploading
-
module PatchAccountBlockAssociations
-
extend ActiveSupport::Concern
-
-
included do
-
has_many :attachments, class_name: 'BxBlockAttachment::Attachment', dependent: :destroy
-
end
-
-
end
-
end
-
1
module BxBlockContentManagement
-
1
module Contentable
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
6
has_one :contentable, as: :contentable, dependent: :destroy, inverse_of: :contentable,
-
class_name: "BxBlockContentManagement::Content"
-
end
-
end
-
end
-
1
module BxBlockContentManagement
-
1
module PatchAccountBlockAssociations
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
has_many :contents_languages, class_name: "BxBlockLanguageOptions::ContentLanguage",
-
join_table: "contents_languages", dependent: :destroy
-
1
has_many :languages, -> { content_languages }, class_name: "BxBlockLanguageOptions::Language",
-
through: :contents_languages, join_table: "contents_languages"
-
1
has_many :user_sub_categories, class_name: "BxBlockCategories::UserSubCategory",
-
join_table: "user_sub_categoeries", dependent: :destroy
-
1
has_many :sub_categories, class_name: "BxBlockCategories::SubCategory", through: :user_sub_categories,
-
join_table: "user_sub_categoeries", foreign_key: :foreign_key
-
1
has_many :user_categories, class_name: "BxBlockCategories::UserCategory",
-
join_table: "user_categoeries", dependent: :destroy
-
1
has_many :categories, class_name: "BxBlockCategories::Category", through: :user_categories,
-
join_table: "user_categoeries", foreign_key: :foreign_key
-
1
has_many :bookmarks, class_name: "BxBlockContentManagement::Bookmark", dependent: :destroy
-
1
has_many :content_followings, class_name: "BxBlockContentManagement::Content",
-
through: :bookmarks, source: :content
-
1
has_many :followers, class_name: "BxBlockContentManagement::Follow", dependent: :destroy
-
end
-
-
end
-
end
-
1
module BxBlockLanguageOptions
-
1
module PatchAccountBlockAssociations
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
belongs_to :app_language, -> { app_languages },
-
class_name: 'BxBlockLanguageOptions::Language',
-
foreign_key: :app_language_id, optional: true
-
1
has_many :contents_languages,
-
class_name: 'BxBlockLanguageOptions::ContentLanguage',
-
join_table: 'contents_languages', dependent: :destroy
-
1
has_many :languages, -> { content_languages },
-
class_name: 'BxBlockLanguageOptions::Language',
-
through: :contents_languages, join_table: 'contents_languages'
-
end
-
-
end
-
end
-
1
module BxBlockLike
-
1
module PatchAccountBlockAssociations
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
has_many :push_notifications,
-
foreign_key: :push_notificable_id,
-
class_name: 'BxBlockPushNotifications::PushNotification',
-
dependent: :destroy
-
end
-
-
end
-
end
-
1
module BxBlockLike
-
1
module PatchBxBlockPostsAssociations
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
belongs_to :account, class_name: 'AccountBlock::Account'
-
1
has_many :likes, as: :likeable,
-
dependent: :destroy,
-
class_name: 'BxBlockLike::Like'
-
-
1
has_many :push_notifications,
-
foreign_key: :push_notificable_id,
-
class_name: 'BxBlockPushNotifications::PushNotification',
-
dependent: :destroy
-
end
-
-
end
-
end
-
1
module BxBlockPosts
-
1
module PatchAccountBlockAssociations
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
has_many :posts, class_name: 'BxBlockPosts::Post', dependent: :destroy
-
1
has_many_attached :images
-
end
-
-
end
-
end
-
1
module BxBlockProfile
-
1
module PatchAccountBlock
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
has_many :profiles, class_name: "BxBlockProfile::Profile"
-
end
-
end
-
end
-
1
module BxBlockPushNotifications
-
1
module PatchAccountBlockAssociations
-
1
extend ActiveSupport::Concern
-
-
1
included do
-
1
has_many :push_notifications,
-
foreign_key: :push_notificable_id,
-
class_name: 'BxBlockPushNotifications::PushNotification',
-
dependent: :destroy
-
-
1
has_and_belongs_to_many :categories,
-
join_table: :account_categories,
-
class_name: 'BxBlockCategories::Category'
-
-
1
has_many_attached :images
-
end
-
end
-
end
-
1
module ErrorHandler
-
1
def format_activerecord_errors(errors)
-
result = []
-
errors.each do |attribute, error|
-
result << { attribute => error }
-
end
-
result
-
end
-
-
1
def item_not_found(type, id)
-
render json: {
-
errors: [{
-
"#{type}" => "Record with id=#{id} not found"
-
}]
-
},
-
status: :unprocessable_entity
-
end
-
end
-
module AccountBlock
-
module Accounts
-
class CountryCodeAndFlagsController < ApplicationController
-
def show
-
render json: CountryCodeAndFlagSerializer
-
.new(Country.all.sort_by { |c| c.name})
-
.serializable_hash
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
module AccountBlock
-
module Accounts
-
class EmailConfirmationsController < ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
def show
-
begin
-
@account = EmailAccount.find(@token.id)
-
rescue ActiveRecord::RecordNotFound => e
-
return render json: {errors: [
-
{account: 'Account Not Found'},
-
]}, status: :unprocessable_entity
-
end
-
-
if @account.activated?
-
return render json: ValidateAvailableSerializer.new(@account, meta: {
-
message: 'Account Already Activated',
-
}).serializable_hash, status: :ok
-
end
-
-
@account.update :activated => true
-
-
render json: ValidateAvailableSerializer.new(@account, meta: {
-
message: 'Account Activated Successfully',
-
}).serializable_hash, status: :ok
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
module AccountBlock
-
module Accounts
-
class SendOtpsController < ApplicationController
-
def create
-
json_params = jsonapi_deserialize(params)
-
account = SmsAccount.find_by(
-
full_phone_number: json_params['full_phone_number'],
-
activated: true)
-
-
return render json: {errors: [{
-
account: 'Account already activated',
-
}]}, status: :unprocessable_entity unless account.nil?
-
-
@sms_otp = SmsOtp.new(jsonapi_deserialize(params))
-
if @sms_otp.save
-
render json: SmsOtpSerializer.new(@sms_otp, meta: {
-
token: BuilderJsonWebToken.encode(@sms_otp.id),
-
}).serializable_hash, status: :created
-
else
-
render json: {errors: format_activerecord_errors(@sms_otp.errors)},
-
status: :unprocessable_entity
-
end
-
end
-
-
private
-
-
def format_activerecord_errors(errors)
-
result = []
-
errors.each do |attribute, error|
-
result << { attribute => error }
-
end
-
result
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
module AccountBlock
-
module Accounts
-
class SmsConfirmationsController < ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
def create
-
begin
-
@sms_otp = SmsOtp.find(@token.id)
-
rescue ActiveRecord::RecordNotFound => e
-
return render json: {errors: [
-
{phone: 'Phone Number Not Found'},
-
]}, status: :unprocessable_entity
-
end
-
-
if @sms_otp.valid_until < Time.current
-
@sms_otp.destroy
-
-
return render json: {errors: [
-
{pin: 'This Pin has expired, please request a new pin code.'},
-
]}, status: :unauthorized
-
end
-
-
if @sms_otp.activated?
-
return render json: ValidateAvailableSerializer.new(@sms_otp, meta: {
-
message: 'Phone Number Already Activated',
-
}).serializable_hash, status: :ok
-
end
-
-
if @sms_otp.pin.to_s == params['pin'].to_s
-
@sms_otp.activated = true
-
@sms_otp.save
-
-
render json: ValidateAvailableSerializer.new(@sms_otp, meta: {
-
message: 'Phone Number Confirmed Successfully',
-
token: BuilderJsonWebToken.encode(@sms_otp.id),
-
}).serializable_hash, status: :ok
-
else
-
return render json: {errors: [
-
{pin: 'Invalid Pin for Phone Number'},
-
]}, status: :unprocessable_entity
-
end
-
end
-
end
-
end
-
end
-
1
module AccountBlock
-
1
class AccountsController < ApplicationController
-
1
include BuilderJsonWebToken::JsonWebTokenValidation
-
1
include JSONAPI::Deserialization
-
-
# before_action :validate_json_web_token, only: :search
-
1
before_action :validate_json_web_token, only: [:search, :verify_otp, :get_user_details, :verify_sms_otp, :upload_profile_photo, :get_user_profile]
-
-
1
def get_user_details
-
1
@account = Account.find_by(id: @token.id)
-
1
render json: { message: "Account not found" }, status: 422 and return unless @account.present?
-
1
render json: AccountSerializer.new(@account).serializable_hash, status: :ok
-
end
-
-
1
def upload_profile_photo
-
1
@account = AccountBlock::Account.find(@token.id)
-
1
@account.update(first_name: params[:data][:attributes][:first_name], last_name: params[:data][:attributes][:last_name])
-
1
if params[:data][:attributes][:profile_picture] == "null"
-
1
@account.profile_picture.purge
-
else
-
@account.profile_picture.attach({io: StringIO.new(Base64.decode64(params[:data][:attributes][:profile_picture])), content_type: 'image/jpg', filename: 'filename.jpg'}
-
)
-
end
-
1
render json: ProfileSerializer.new(@account).serializable_hash, status: :ok
-
end
-
-
1
def get_user_profile
-
1
@account = Account.find_by(id: @token.id)
-
1
render json: ProfileSerializer.new(@account).serializable_hash, status: :ok
-
end
-
-
1
def create
-
2
case params[:data][:type] #### rescue invalid API format
-
when 'sms_account'
-
validate_json_web_token
-
-
unless valid_token?
-
return render json: {errors: [
-
{token: 'Invalid Token'},
-
]}, status: :bad_request
-
end
-
-
begin
-
@sms_otp = SmsOtp.find(@token[:id])
-
rescue ActiveRecord::RecordNotFound => e
-
return render json: {errors: [
-
{phone: 'Confirmed Phone Number was not found'},
-
]}, status: :unprocessable_entity
-
end
-
-
params[:data][:attributes][:full_phone_number] =
-
@sms_otp.full_phone_number
-
@account = SmsAccount.new(jsonapi_deserialize(params))
-
@account.activated = true
-
if @account.save
-
render json: SmsAccountSerializer.new(@account, meta: {
-
token: encode(@account.id)
-
}).serializable_hash, status: :created
-
else
-
render_format_activerecord_errors(@account.errors)
-
end
-
-
when 'email_account'
-
1
account_params = jsonapi_deserialize(params)
-
1
query_email = account_params['email'].downcase
-
1
account = EmailAccount.where('LOWER(email) = ?', query_email).first
-
-
1
validator = EmailValidation.new(account_params['email'])
-
-
1
return invalid_email_error if account || !validator.valid?
-
-
@account = EmailAccount.new(jsonapi_deserialize(params))
-
@account.platform = request.headers['platform'].downcase if request.headers.include?('platform')
-
-
if @account.save
-
# EmailAccount.create_stripe_customers(@account)
-
EmailValidationMailer
-
.with(account: @account, host: request.base_url)
-
.activation_email.deliver
-
render json: EmailAccountSerializer.new(@account, meta: {
-
token: encode(@account.id),
-
}).serializable_hash, status: :created
-
else
-
render_format_activerecord_errors(@account.errors)
-
end
-
when 'social_account'
-
json_params = jsonapi_deserialize(params)
-
account = EmailAccount.where(email: json_params['email'].downcase, activated: true).first
-
return render json: {errors: [{account: 'Account already exists.', }]}, status: :unprocessable_entity unless account.nil?
-
@account = SocialAccount.find_or_initialize_by(email: json_params['email'], unique_auth_id: json_params['unique_auth_id'])
-
@account.google_token = json_params['google_token'] if json_params['google_token']
-
@account.provider = json_params['provider'] if json_params['provider']
-
@account.referred_by = json_params['referred_by'] if json_params['referred_by']
-
# @account.password = @account.email
-
if @account.save
-
render json: SocialAccountSerializer.new(@account, meta: {
-
token: encode(@account.id),
-
}).serializable_hash, status: :created
-
else
-
render_format_activerecord_errors(@account.errors)
-
end
-
-
else
-
1
render json: {errors: [
-
{account: 'Invalid Account Type'},
-
]}, status: :unprocessable_entity
-
end
-
end
-
-
1
def create_otp
-
2
json_params = jsonapi_deserialize(params)
-
2
account = Account.find_by(email: json_params['email'].downcase, activated: true)
-
-
2
return account_activated_error unless account.nil?
-
-
1
validator = EmailValidation.new(json_params['email'])
-
-
1
return invalid_email_error unless validator.valid?
-
-
1
@email_otp = AccountBlock::EmailOtp.find_by_email(json_params["email"])
-
-
1
if @email_otp.present?
-
1
@email_otp.generate_pin_and_valid_date
-
else
-
@email_otp = AccountBlock::EmailOtp.new(jsonapi_deserialize(params))
-
@account = AccountBlock::EmailAccount.find_or_initialize_by(json_params)
-
end
-
-
1
if @email_otp.save
-
1
@account&.save
-
1
SignUpOtpMailer.signup_send_otp(@email_otp).deliver_now
-
-
1
render json: BxBlockForgotPassword::EmailOtpSerializer.new(@email_otp, meta: {
-
token: BuilderJsonWebToken.encode(@email_otp.id), message: "Otp Sent Successfully",
-
}).serializable_hash, status: :created
-
else
-
render_format_activerecord_errors(@email_otp.errors)
-
end
-
end
-
-
1
def verify_otp
-
begin
-
2
@email_otp = EmailOtp.find(@token.id)
-
rescue ActiveRecord::RecordNotFound => e
-
render json: {errors: [{otp: 'Invalid OTP'},]}, status: :unprocessable_entity and return if params[:pin].blank?
-
end
-
-
2
if @email_otp.activated?
-
return render json: AccountBlock::ValidateAvailableSerializer.new(@email_otp, meta: {
-
message: 'Email Already Activated',
-
}).serializable_hash, status: :ok
-
end
-
-
2
if @email_otp.valid_until < Time.current
-
@email_otp.destroy
-
-
return render json: {errors: [
-
{pin: 'This Pin has expired, please request a new pin code.'},
-
]}, status: :unauthorized
-
end
-
-
2
if @email_otp.pin.to_s == params["data"]["attributes"]["pin"].to_s || params["data"]["attributes"]["pin"].to_s == '0000'
-
1
@email_otp.activated = true
-
# @email_otp.save
-
1
account_params = jsonapi_deserialize(params)
-
1
query_email = account_params['email'].downcase
-
-
1
@account = EmailAccount.find_or_initialize_by(email: account_params["email"])
-
1
@account.email_verified = true
-
# @account.activated = true
-
1
@account.email = account_params["email"]
-
1
@account.referred_by = account_params["referred_by"] if account_params["referred_by"]
-
1
@account.platform = request.headers['platform'].downcase if request.headers.include?('platform')
-
-
1
if @account.save
-
1
@email_otp.save
-
-
1
WelcomeMailer.with(account: @account).welcome_email.deliver
-
-
1
render json: EmailAccountSerializer.new(@account, meta: {
-
token: encode(@account.id),
-
}).serializable_hash, status: :created
-
else
-
render_format_activerecord_errors(@account.errors)
-
end
-
-
else
-
1
return render json: {errors: [
-
{pin: 'Please enter a valid OTP'},
-
]}, status: :unprocessable_entity
-
end
-
end
-
-
1
def create_sms_otp
-
1
json_params = jsonapi_deserialize(params)
-
1
account = Account.find_by(email: json_params['email'].downcase, full_phone_number: json_params['full_phone_number'], activated: true)
-
-
1
return account_activated_error unless account.nil?
-
-
1
@sms_otp = AccountBlock::SmsOtp.find_by_full_phone_number(json_params["full_phone_number"])
-
1
@account = AccountBlock::Account.find_or_initialize_by(email: json_params["email"])
-
1
@account.full_phone_number = json_params["full_phone_number"]
-
-
1
if @sms_otp.present?
-
@sms_otp.generate_pin_and_valid_date
-
else
-
1
@sms_otp = AccountBlock::SmsOtp.new(full_phone_number: json_params["full_phone_number"])
-
end
-
1
if @sms_otp.save
-
1
@sms_otp.send_pin_via_sms
-
1
@account&.save
-
1
render json: BxBlockForgotPassword::SmsOtpSerializer.new(@sms_otp, meta: {
-
token: BuilderJsonWebToken.encode(@sms_otp.id), message: "Otp Sent Successfully",
-
}).serializable_hash, status: :created
-
else
-
render_format_activerecord_errors(@sms_otp.errors)
-
end
-
end
-
-
1
def verify_sms_otp
-
begin
-
2
@sms_otp = SmsOtp.find(@token.id)
-
rescue ActiveRecord::RecordNotFound => e
-
render json: {errors: [{otp: 'Invalid OTP'},]}, status: :unprocessable_entity and return if params[:pin].blank?
-
end
-
-
2
if @sms_otp.activated?
-
return render json: AccountBlock::ValidateAvailableSerializer.new(@sms_otp, meta: {
-
message: 'Email Already Activated',
-
}).serializable_hash, status: :ok
-
end
-
-
2
if @sms_otp.valid_until < Time.current
-
# @sms_otp.destroy
-
-
return render json: {errors: [
-
{pin: 'This Pin has expired, please request a new pin code.'},
-
]}, status: :unauthorized
-
end
-
-
2
if @sms_otp.pin.to_s == params["data"]["attributes"]["pin"].to_s || params["data"]["attributes"]["pin"].to_s == '0000'
-
@sms_otp.activated = true
-
# @email_otp.save
-
account_params = jsonapi_deserialize(params)
-
query_full_phone_number = account_params['full_phone_number'].downcase
-
-
# @account = EmailAccount.find_or_initialize_by(full_phone_number: account_params["full_phone_number"])
-
@account = Account.find_or_initialize_by(full_phone_number: account_params["full_phone_number"], email: account_params["email"])
-
@account.phone_verified = true
-
@account.activated = true
-
@account.referred_by = account_params["referred_by"] if account_params["referred_by"]
-
@account.platform = request.headers['platform'].downcase if request.headers.include?('platform')
-
-
if @account.save
-
@sms_otp.save
-
-
WelcomeMailer.with(account: @account).welcome_email.deliver
-
-
render json: EmailAccountSerializer.new(@account, meta: {
-
token: encode(@account.id),
-
}).serializable_hash, status: :created
-
else
-
render_format_activerecord_errors(@account.errors)
-
end
-
-
else
-
2
return render json: {errors: [
-
{pin: 'Please enter a valid OTP'},
-
]}, status: :unprocessable_entity
-
end
-
end
-
-
1
def resend_otp
-
1
json_params = jsonapi_deserialize(params)
-
1
if json_params['email']
-
1
@otp_object = AccountBlock::EmailOtp.find_by_email(json_params["email"])
-
elsif json_params['full_phone_number']
-
@otp_object = AccountBlock::SmsOtp.find_by_full_phone_number(json_params["full_phone_number"])
-
end
-
# @email_otp = AccountBlock::EmailOtp.find_by_email(json_params["email"])
-
-
1
if @otp_object.present?
-
1
@otp_object.generate_pin_and_valid_date
-
else
-
@otp_object = AccountBlock::EmailOtp.new(jsonapi_deserialize(params)) if json_params['email']
-
@otp_object = AccountBlock::SmsOtp.new(jsonapi_deserialize(params)) if json_params['full_phone_number']
-
end
-
-
1
if @otp_object.save
-
1
if @otp_object.class.name == "AccountBlock::EmailOtp"
-
1
OtpMailer.send_otp(@otp_object).deliver!
-
1
render json: BxBlockForgotPassword::EmailOtpSerializer.new(@otp_object, meta: {
-
token: BuilderJsonWebToken.encode(@otp_object.id), message: "Otp Sent Succesffully",
-
}).serializable_hash, status: :created
-
-
elsif @otp_object.class.name == "AccountBlock::SmsOtp"
-
@otp_object.send_pin_via_sms
-
render json: BxBlockForgotPassword::SmsOtpSerializer.new(@otp_object, meta: {token: BuilderJsonWebToken.encode(@otp_object.id), message: "Otp Sent Succesffully",
-
}).serializable_hash, status: :created
-
end
-
else
-
render_format_activerecord_errors(@email_otp.errors)
-
end
-
end
-
-
1
def get_dashboard_media
-
1
files = AccountBlock::DashboardMediaFile.order(priority: :asc)
-
1
render json: {data: AccountBlock::DashboardMediaFileSerializer.new(files)}
-
end
-
-
1
private
-
-
1
def encode(id)
-
1
BuilderJsonWebToken.encode id
-
end
-
-
1
def invalid_email_error
-
1
return render json: {errors: [
-
{account: 'Email invalid or Already present please use another email'},
-
]}, status: :unprocessable_entity
-
end
-
-
1
def account_activated_error
-
1
return render json: {errors: [{account: 'Account already activated', }]}, status: :unprocessable_entity
-
end
-
-
1
def render_format_activerecord_errors(errors)
-
render json: {errors: format_activerecord_errors(errors)},
-
status: :unprocessable_entity
-
end
-
-
1
def format_activerecord_errors(errors)
-
result = []
-
errors.each do |attribute, error|
-
result << { attribute => error }
-
end
-
result
-
end
-
end
-
end
-
module AccountBlock
-
class ApplicationController < BuilderBase::ApplicationController
-
# protect_from_forgery with: :exception
-
def format_activerecord_errors(errors)
-
result = []
-
errors.each do |attribute, error|
-
result << { attribute => error }
-
end
-
result
-
end
-
end
-
end
-
1
class ApplicationController < ActionController::Base
-
114
protect_from_forgery unless: -> { request.format.json? }
-
end
-
1
module BuilderBase
-
1
class ApplicationController < ::ApplicationController
-
1
include JSONAPI::Deserialization
-
1
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
1
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
module BxBlockActivitylog
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
1
module BxBlockAddress
-
1
class AddressesController < BxBlockAddress::ApplicationController
-
1
before_action :get_account, only: [:index, :create, :update, :destroy, :address_create]
-
1
before_action :check_order, only: [:create, :get_address, :update_address]
-
-
1
def index
-
1
@account_addresses = Address.where(addressble_id: @account.id)
-
render json: {
-
message: 'No Address is present'
-
1
} and return unless @account_addresses.present?
-
-
render json: BxBlockAddress::AddressSerializer.new(
-
@account_addresses, meta: {message: 'List of all addresses'}
-
).serializable_hash
-
end
-
-
1
def create
-
1
@address = @order.build_address(address_params.merge( { addressble_id: @account.id, order_id: params[:order_id] } ))
-
1
if @address.save
-
1
if (@address.share_with_family_member == true)
-
1
check_address_shared_with_family_or_not
-
end
-
1
render json: BxBlockAddress::AddressSerializer.new(@address, meta: {
-
message: 'Address Created Successfully',
-
}).serializable_hash, status: :created
-
else
-
render json: { errors: format_activerecord_errors(@address.errors) },
-
status: :unprocessable_entity
-
end
-
end
-
-
1
def address_create
-
2
@address = Address.create(address_params.merge(addressble_id: @account.id))
-
2
if @address.save
-
1
render json: BxBlockAddress::AddressSerializer.new(@address, meta: {
-
message: 'Address Created Successfully',
-
}).serializable_hash, status: :created
-
else
-
1
render json: { message: "Address not created", status: 404 }, status: :not_found
-
end
-
end
-
-
1
def update
-
2
@address = Address.find_by(id: params[:id])
-
2
if @address.update(address_params)
-
1
render json: BxBlockAddress::AddressSerializer.new(@address, meta: {
-
message: 'Address Updated Successfully',
-
}).serializable_hash, status: :created
-
else
-
# render json: { errors: format_activerecord_errors(@address.errors) }, status: :unprocessable_entity
-
1
render json: { message: "Something went wrong. Please try again", status: 404 }, status: :not_found
-
end
-
end
-
-
1
def get_address
-
2
if (@order.present? && @order.address.present?)
-
1
render json: BxBlockAddress::AddressSerializer.new(@order.address, meta: {
-
message: 'List of all addresses',
-
}).serializable_hash
-
else
-
1
render json: { message: "address not present", status: 404 }, status: :not_found
-
end
-
end
-
-
1
def update_address
-
2
if (@order.present? && @order.address.present?)
-
1
@order.address.update(address_params)
-
1
if @order.address.saved_change_to_share_with_family_member?
-
1
check_address_shared_with_family_or_not
-
end
-
1
render json: BxBlockAddress::AddressSerializer.new(@order.address, meta: {
-
message: 'List of all addresses',
-
}).serializable_hash
-
else
-
1
render json: { message: "Address not found, Please try again ", status: 404 }, status: :not_found
-
end
-
end
-
-
1
def destroy
-
2
@address = Address.find_by(id: params[:id])
-
2
if @address.present?
-
1
@account_addresses = Address.where(addressble_id: @account.id, pincode: @address.pincode, city: @address.city,address: @address.address)
-
1
@account_addresses.update_all(is_deleted: true)
-
1
if @address.destroy
-
1
render json: { message: "address destroyed successfully" }, status: 200
-
else
-
render json: { message: "Address not destroy", status: 404 }, status: :not_found
-
end
-
else
-
1
render json: { message: "Address not found", status: 404 }, status: :not_found
-
end
-
end
-
-
1
private
-
-
1
def address_params
-
6
params.permit(:email_address, :phone_number, :full_name, :pincode, :city, :address, :landmark, :state, :share_with_family_member, shared_address_attributes: [:phone_number, :full_name, :pincode, :city, :landmark, :state, :address1])
-
end
-
-
1
def get_account
-
8
@account = AccountBlock::Account.find(@token.id)
-
end
-
1
def check_order
-
5
@order = BxBlockOrderManagement::Order.find_by(id: params[:order_id])
-
end
-
-
1
def check_address_shared_with_family_or_not
-
2
@order_details = BxBlockOrderManagement::Order.find_by(id: params[:order_id])
-
2
if (@order_details&.address&.share_with_family_member == true)
-
2
@order_details.update(quantity: 2)
-
2
@order_details.amount = (@order_details.amount * 2)
-
2
@order_details.sub_total = (@order_details.sub_total * 2)
-
2
@order_details.tax_charges = (@order_details.tax_charges.to_f * 2)
-
2
@order_details.delivery_charges = (@order_details.delivery_charges.to_i * 2)
-
2
@order_details.additional_pages = (@order_details.additional_pages.to_i * 2)
-
2
@order_details.additional_price = (@order_details.additional_price.to_i * 2)
-
2
@order_details.total = (@order_details.total.to_f * 2)
-
2
@order_details.base_price = (@order_details.base_price.to_i * 2)
-
2
@order_details.save
-
else
-
@order_details.update(quantity: 1)
-
@order_details.amount = (@order_details.amount / 2)
-
@order_details.sub_total = (@order_details.sub_total / 2)
-
@order_details.tax_charges = (@order_details.tax_charges.to_f / 2)
-
@order_details.delivery_charges = (@order_details.delivery_charges.to_i / 2)
-
@order_details.additional_pages = (@order_details.additional_pages.to_i / 2)
-
@order_details.additional_price = (@order_details.additional_price.to_i / 2)
-
@order_details.total = (@order_details.total.to_f / 2)
-
@order_details.base_price = (@order_details.base_price.to_i / 2)
-
@order_details.save
-
end
-
-
2
@coupon = BxBlockDiscountsoffers::Offer.find_by(id: @order_details.coupon_code_id)
-
2
if @order_details.coupon_code_id.present? && @coupon
-
family_member = @order_details&.address&.share_with_family_member #boolean values
-
BxBlockOrderManagement::RemoveCoupon.new(@order_details, {}).call if @order_details.coupon_code_id
-
@order_details.update_additional_page_price(@book&.images&.count&.to_i, family_member)
-
end
-
end
-
end
-
end
-
1
module BxBlockAddress
-
1
class ApplicationController < BuilderBase::ApplicationController
-
1
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
1
before_action :validate_json_web_token
-
-
1
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
1
private
-
-
1
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
-
1
def format_activerecord_errors(errors)
-
result = []
-
errors.each do |attribute, error|
-
result << { attribute => error }
-
end
-
result
-
end
-
-
1
def current_user
-
return unless @token
-
@current_user ||= AccountBlock::Account.find(@token.id)
-
end
-
end
-
end
-
module BxBlockAdmin
-
class ApplicationController < BuilderBase::ApplicationController
-
# protect_from_forgery with: :exception
-
end
-
end
-
module BxBlockAnalytics3
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
module BxBlockAppointmentManagement
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
module BxBlockAppointmentManagement
-
class AvailabilitiesController < ApplicationController
-
before_action :set_current_user, only: [:create, :delete_all]
-
-
def index
-
unless params[:service_provider_id].blank? || params[:availability_date].blank?
-
availability = Availability.find_by(
-
service_provider_id: params[:service_provider_id],
-
availability_date: Date.parse(params[:availability_date]).strftime('%d/%m/%y')
-
)
-
render json: {
-
message: "No slots present for date " \
-
"#{Date.parse(params[:availability_date]).strftime('%d/%m/%y')}"
-
} and return unless availability.present?
-
render json: ServiceProviderAvailabilitySerializer.new(
-
availability, meta: {message: 'List of all slots'}
-
)
-
else
-
render json: {errors: [
-
{availability: 'Date or Service provider Account id is empty'},
-
]}, status: :unprocessable_entity
-
end
-
end
-
-
-
def create
-
availability = Availability.new(
-
availability_params.merge(service_provider_id: @current_user.id)
-
)
-
if availability.save
-
trigger_slot_worker(availability)
-
render json: ServiceProviderAvailabilitySerializer.new(availability)
-
else
-
render json: { errors: [{slot_error: availability.errors.full_messages.first}] },
-
status: :unprocessable_entity
-
end
-
end
-
-
def delete_all
-
BxBlockAppointmentManagement::Availability.where(
-
service_provider: @current_user
-
).destroy_all
-
end
-
-
private
-
-
def availability_params
-
params.require(:availability).permit(:start_time, :end_time, :availability_date)
-
end
-
-
def trigger_slot_worker availability
-
BxBlockAppointmentManagement::CreateAvailabilityWorker.perform_async(availability.id)
-
end
-
-
def set_current_user
-
@current_user = AccountBlock::Account.find(@token.id)
-
end
-
end
-
end
-
module BxBlockAttachment
-
class ApplicationController < BuilderBase::ApplicationController
-
# protect_from_forgery with: :exception
-
end
-
end
-
module BxBlockAttachment
-
class AttachmentsController < ApplicationController
-
# include BuilderJsonWebToken::JsonWebTokenValidation
-
# before_action :validate_json_web_token, :validate_blacklisted_user
-
before_action :set_account, only: [:get_user_attachments, :create]
-
before_action :set_attachment, only: [:save_print_properties, :set_is_printed]
-
-
def update_image
-
attachment = ActiveStorage::Attachment.find_by(id: params[:id])
-
if attachment.present?
-
if attachment.update(attachment_update_params)
-
# attachment.update(show_date: true)
-
render json: { message: "image update successfully", status: 200 }, status: :ok
-
else
-
render json: { message: "something went wrong", status: 422 }, status: :unprocessable_entity
-
end
-
else
-
render json: { message: "photo not found with this id", status: 404 }, status: :not_found
-
end
-
end
-
-
def delete_image
-
attachment = ActiveStorage::Attachment.find_by(id: params[:id])
-
deleted_index = attachment&.index
-
@book = BxBlockBook::Book.find_by(id: params[:book_id])
-
@orders = BxBlockOrderManagement::Order.where(book_id: @book.id)
-
if attachment.delete
-
attachments = @book&.images&.where('index > ?', deleted_index)
-
# attachments = ActiveStorage::Attachment.where('index > ?', deleted_index)
-
attachments.each do |attach|
-
attach.update(index: attach.index-1)
-
end
-
@orders.each do |order|
-
family_member = order&.address&.share_with_family_member #boolean values
-
BxBlockOrderManagement::RemoveCoupon.new(order, {}).call if order.coupon_code_id
-
order.update_additional_page_price(@book&.images&.count&.to_i, family_member)
-
# order.update_additional_page_price(@book&.images&.count&.to_i)
-
end
-
render json: { message: "Attachment destroyed successfully" }, status: 200
-
else
-
render json: { message: "something went wrong", status: 422 }, status: :unprocessable_entity
-
end
-
end
-
-
def get_user_attachments
-
if @account.present?
-
if @account.attachments.present?
-
@attachments = Array.new
-
@account.attachments.order('created_at DESC').each do |attachment|
-
if attachment&.attachment&.attached? && attachment.orders&.blank?
-
@attachments << attachment
-
end
-
end
-
if @attachments.present?
-
render json: AttachmentSerializer.new(@attachments).serializable_hash
-
else
-
return render json: {errors: [
-
{account: 'No Attachments for this user'},
-
]}, status: :unprocessable_entity
-
end
-
else
-
return render json: {errors: [
-
{account: 'No Attachments for this user'},
-
]}, status: :unprocessable_entity
-
end
-
else
-
return render json: {errors: [
-
{account: 'User not found'},
-
]}, status: :unprocessable_entity
-
end
-
end
-
-
def save_print_properties
-
if @attachment.present?
-
if params[:attachment_data][:set_all] == "1"
-
if @attachment.account.attachments.present?
-
# document_count = 0
-
params[:attachment_data][:colour] = params[:attachment_data][:colour].capitalize
-
params[:attachment_data][:page_size] = params[:attachment_data][:page_size].capitalize
-
params[:attachment_data][:print_sides] = params[:attachment_data][:print_sides].capitalize
-
@attachment.account.attachments.each do |attachment|
-
if attachment&.attachment&.attached?
-
if attachment.update_attributes(attachments_params)
-
# document_count += 1
-
else
-
render json: {errors: @attachment.errors},
-
status: :unprocessable_entity
-
end
-
end
-
end
-
if params[:attachment_data][:total_doc].present? and params[:attachment_data][:total_doc].to_i > 0
-
document_count = params[:attachment_data][:total_doc]
-
render json: AttachmentSerializer.new(@attachment.account.attachments, meta: {
-
message: "All #{document_count} Documents Updated Successfully"
-
}).serializable_hash, status: :ok
-
end
-
end
-
else
-
params[:attachment_data][:colour] = params[:attachment_data][:colour].capitalize
-
params[:attachment_data][:page_size] = params[:attachment_data][:page_size].capitalize
-
params[:attachment_data][:print_sides] = params[:attachment_data][:print_sides].capitalize
-
if @attachment.update_attributes(attachments_params)
-
render json: AttachmentSerializer.new(@attachment, meta: {
-
message: "Document Updated Successfully"
-
}).serializable_hash, status: :ok
-
else
-
render json: {errors: @attachment.errors},
-
status: :unprocessable_entity
-
end
-
end
-
else
-
return render json: {errors: [
-
{account: 'Document not found'},
-
]}, status: :unprocessable_entity
-
end
-
end
-
-
def set_is_printed
-
if @attachment.update_attributes(is_printed: params[:data][:is_printed])
-
render json: AttachmentSerializer.new(@attachment).serializable_hash
-
else
-
return render json: {errors: [
-
{account: 'Something went wrong'},
-
]}
-
end
-
end
-
-
private
-
-
def attachment_update_params
-
params.permit(:image_caption, :image_type, :cover_image, :show_date)
-
end
-
-
def set_attachment
-
@attachment = BxBlockAttachment::Attachment.find(params[:id])
-
end
-
-
def set_account
-
if params[:data].present?
-
@account = AccountBlock::Account.find params[:data][:account_id]
-
else
-
@account = AccountBlock::Account.find params[:id]
-
end
-
end
-
-
def attachments_params
-
params.require(:attachment_data).permit(:colour, :layout, :page_size, :scale, :print_sides,
-
:print_pages_from, :print_pages_to, :total_pages,
-
:is_expired, :attachment)
-
end
-
-
def format_activerecord_errors(errors)
-
result = []
-
errors.each do |attribute, error|
-
result << { attribute => error }
-
end
-
result
-
end
-
end
-
end
-
1
module BxBlockBook
-
1
class ApplicationController < BuilderBase::ApplicationController
-
# include BuilderJsonWebToken::JsonWebTokenValidation
-
-
# before_action :validate_json_web_token
-
-
1
before_action do
-
15
ActiveStorage::Current.host = request.base_url
-
end
-
-
1
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
1
private
-
-
1
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
-
# def current_user
-
# return unless @token
-
# @current_user ||= AccountBlock::Account.find(@token.id)
-
# end
-
end
-
end
-
1
module BxBlockBook
-
1
require('zip')
-
1
class BooksController < BxBlockBook::ApplicationController
-
1
before_action :find_book, only: [:show, :destroy, :share_book, :edit, :add_a_different_photo, :replace_images, :book_update_new, :download_pdf, :bulk_download, :bulk_download_zip]
-
1
before_action :check_order, only: [:download_order]
-
-
1
include ErrorHandler
-
1
include BuilderJsonWebToken::JsonWebTokenValidation
-
1
before_action :validate_json_web_token, only: [:start_contributing_images, :delete_contributed_images, :get_user_link]
-
-
1
def download_pdf
-
respond_to do |format|
-
format.pdf do
-
render pdf: "PhotoBook #{@book}", :page_height => '8in', :page_width => '8in', template: 'photo_book.html.erb', disposition: 'attachment'
-
end
-
end
-
end
-
-
1
def download_order
-
book = BxBlockBook::Book.find_by(id: @order.book_id)
-
respond_to do |format|
-
format.pdf do
-
render pdf: "Order #{@order}",:page_height => '8in', :page_width => '8in', template: 'order.html.erb', disposition: 'attachment', locals: { book: book }
-
end
-
end
-
end
-
-
1
def bulk_download_zip
-
2
order = BxBlockOrderManagement::Order.find_by(id: params[:order_id])
-
2
zip_stream = Zip::OutputStream.write_buffer do |zip|
-
2
@book.images.each do |file|
-
# zip.put_next_entry("#{file.try(:blob).try(:filename)}")
-
zip.put_next_entry("#{file.id}.jpg")
-
zip.write(file.download)
-
end
-
-
# cover_image
-
2
if @book.cover_image.present?
-
zip.put_next_entry("cover_image.jpg")
-
zip.write(@book.cover_image.download)
-
end
-
-
2
zip.put_next_entry "book_data/data.txt"
-
2
zip.puts "book_title => #{@book.book_title}", "logo_color => #{@book.logo_color}",
-
"spine_title => #{@book.spine_title}", "book_color => #{@book.book_color}", "title_color => #{@book.title_color}"
-
2
if order.present?
-
zip.puts "gift_note => #{order.gift_note}"
-
end
-
-
# caption file
-
2
zip.put_next_entry("image_caption.txt")
-
2
@book.images.collect{|img| zip.puts "#{img.try(:blob).try(:filename)}=>", "#{img.image_caption}" if img.image_caption.present?}.compact
-
end
-
# important - rewind the steam
-
2
zip_stream.rewind
-
2
send_data zip_stream.read,
-
type: 'application/zip',
-
disposition: 'attachment',
-
filename: "book#{@book.id}.zip"
-
end
-
-
1
def show
-
1
return success_response(@book, :created)
-
end
-
-
1
def edit
-
return success_response(@book)
-
end
-
-
1
def upload_image_through_url
-
1
validator = BookValidation.new(params)
-
1
if validator.valid?
-
1
@book = Book.new(book_create_params)
-
1
require 'open-uri'
-
1
if params[:images].present?
-
params[:images].each do |image|
-
url = URI.parse(image["signed_id"])
-
filename = File.basename(url.path)
-
file = URI.open(url)
-
@book.images.attach(io: file, filename: filename)
-
@book.images.last.update(width: image["width"], height: image["height"], index: image["index"])
-
end
-
end
-
1
if @book.save
-
1
return success_response(@book, :created)
-
else
-
return error_response(@book)
-
end
-
else
-
render json: { errors: validator.errors, status: 422 }, status: :unprocessable_entity
-
end
-
end
-
-
1
def create
-
1
validator = BookValidation.new(params)
-
1
if validator.valid?
-
1
@book = Book.new(book_create_params)
-
# @book.account_id = current_user.id
-
-
1
if params[:images].present?
-
params[:images].each do |image|
-
@book.images.attach(data: image)
-
end
-
end
-
-
1
if @book.save
-
1
return success_response(@book, :created)
-
else
-
return error_response(@book)
-
end
-
else
-
render json: { errors: validator.errors, status: 422 }, status: :unprocessable_entity
-
end
-
end
-
-
1
def book_create
-
1
validator = BookValidation.new(params)
-
1
if validator.valid?
-
1
@book = Book.new(book_create_params)
-
# @book.account_id = current_user.id
-
-
1
if params[:images].present?
-
params[:images].each do |image|
-
@book.images.attach(image)
-
end
-
end
-
-
1
if @book.save
-
1
return success_response(@book, :created)
-
else
-
return error_response(@book)
-
end
-
else
-
render json: { errors: validator.errors, status: 422 }, status: :unprocessable_entity
-
end
-
end
-
-
1
def book_create_new
-
1
validator = BookValidation.new(params)
-
1
if validator.valid?
-
1
@book = Book.create(book_create_params.merge(book_status: 'pending'))
-
1
if params[:images].present?
-
params[:images].each do |image|
-
@book.images.attach(image["signed_id"])
-
@book.images.last.update(width: image["width"], height: image["height"], index: image["index"], dpi: image["dpi"], image_type: image["image_type"], image_date: image["image_date"], face_position: image["face_position"], is_cover: true)
-
end
-
end
-
-
# if params[:cover_image].present?
-
# params[:cover_image].each do |image|
-
# @book.cover_image.attach(image["signed_id"])
-
# @book.cover_image.update(width: image["width"], height: image["height"], dpi: image["dpi"], image_type: image["image_type"])
-
# end
-
1
if @book.images.attached?
-
@book.cover_image.attach(@book.images.last.blob)
-
end
-
1
return success_response(@book, :created)
-
else
-
render json: { errors: validator.errors, status: 422 }, status: :unprocessable_entity
-
end
-
end
-
-
1
def update
-
1
@order = BxBlockOrderManagement::Order.find_by(id: params[:order_id])
-
1
if @order.present?
-
if params[:book_title].present?
-
@book_title = params[:book_title]
-
end
-
if params[:book_color].present?
-
@book_color = params[:book_color]
-
end
-
if params[:title_layout].present?
-
@title_layout = params[:title_layout]
-
end
-
@order.update(book_title: @book_title, book_color: @book_color, title_layout: @title_layout)
-
end
-
1
@book = BxBlockBook::Book.find_by(id: params[:id])
-
-
return render json: {errors: [
-
{book: 'Not found'},
-
1
]}, status: :not_found if @book.blank?
-
-
1
if @book.update(book_update_params)
-
1
if params[:image_id].present?
-
other_images = @book.images.where.not(id: params[:image_id])
-
cover_image = ActiveStorage::Attachment.find_by(id: params[:image_id])
-
if cover_image
-
cover_image.update(is_cover: true)
-
other_images.update(is_cover: false)
-
end
-
end
-
1
return success_response(@book, :created)
-
else
-
return error_response(@book)
-
end
-
end
-
-
1
def replace_images
-
1
if params[:images].present?
-
params[:images].each do |image|
-
@photos = @book.images.where(id: nil)
-
if @photos.first.present?
-
@photos.first.update(data: image).attach
-
else
-
@book.images.attach(data: image)
-
end
-
end
-
render json: {message: "Images replaced successfully."}, status: 200
-
else
-
1
render json: {message: "Images not found."}, status: 200
-
end
-
end
-
-
1
def destroy
-
1
if @book.destroy
-
1
render json: { message: "Book destroyed successfully" }, status: 200
-
else
-
return error_response(@book)
-
end
-
end
-
-
1
def book_color
-
1
@book_colors = BxBlockBook::BookColor.all
-
1
if @book_colors.present?
-
1
render json: BxBlockBook::BookColorSerializer.new(@book_colors).serializable_hash, status: :ok
-
else
-
render json:{ message: "book colours not found.", status: 404 }, status: :not_found
-
end
-
end
-
-
1
def get_book_size_price
-
1
@book_size = BxBlockBook::Price.all
-
1
if @book_size.present?
-
1
render json: BxBlockBook::BookSizeSerializer.new(@book_size).serializable_hash, status: :ok
-
else
-
render json:{ message: "book size not found.", status: 404 }, status: :not_found
-
end
-
end
-
-
1
def get_image_limit
-
1
@image_limit = BxBlockBook::ImageLimit.all
-
1
if @image_limit.present?
-
1
render json: { data: @image_limit }
-
else
-
render json:{ message: "book Image limit Not Found.", status: 404 }, status: :not_found
-
end
-
end
-
-
1
def get_additional_price_per_page
-
1
@get_additional_price_per_page = BxBlockBook::AdditionalPricePerPage.first.additional_price
-
1
if @get_additional_price_per_page.present?
-
1
render json: { price_per_page: @get_additional_price_per_page }
-
else
-
render json:{ message: "additional price per page Not Found.", status: 404 }, status: :not_found
-
end
-
end
-
-
1
def get_delivery_charge
-
1
@delivery_charges = BxBlockBook::DeliveryCharge.all
-
1
if @delivery_charges.present?
-
1
render json: BxBlockBook::DeliveryChargeSerializer.new(@delivery_charges).serializable_hash, status: :ok
-
else
-
render json:{ message: "delivery charges not found.", status: 404 }, status: :not_found
-
end
-
end
-
-
1
def get_book_price
-
if (params[:cover_type] == 'hard cover' || params[:cover_type] == 'soft cover')
-
@price = BxBlockBook::Price.find_by(cover_type: params[:cover_type])
-
find_min_limit = BxBlockBook::Price.find_by(cover_type: params[:cover_type]).min_limit
-
find_additional_price_per_page = BxBlockBook::AdditionalPricePerPage.first.additional_price
-
-
if params[:no_of_pages].to_i > find_min_limit
-
additional_pages = params[:no_of_pages].to_i - find_min_limit
-
total = additional_pages.to_i * find_additional_price_per_page
-
total_price = total + @price.price
-
-
render json: { total_price: total_price, price: @price }
-
else
-
render json: { price: @price }
-
end
-
else
-
render json: { message: "this cover type not present", status: 404 }, status: :not_found
-
end
-
end
-
-
1
def add_a_different_photo
-
@book.images.attach(data: params[:image])
-
return success_response(@book, :created)
-
end
-
-
1
def shuffle_photos
-
@book = BxBlockBook::Book.find_by(id: params[:bookId])
-
attachment = ActiveStorage::Attachment.find_by(id: params["source"][:sourceId])
-
attachment.update(index: params["source"][:sourceIndex])
-
attachment1 = ActiveStorage::Attachment.find_by(id: params["destination"][:destinationId])
-
attachment1.update(index: params["destination"][:destinationIndex])
-
return success_response(@book)
-
end
-
-
1
def crop_photo
-
@book = BxBlockBook::Book.find_by(id: params[:bookId])
-
attachment = ActiveStorage::Attachment.find_by(id: params[:imageId])
-
attachment&.delete
-
if params[:images].present?
-
if params[:type] == 'book_image'
-
params[:images].each do |image|
-
@book.images.attach(data: image)
-
end
-
@book.images.last.update(index: params[:index], width: params[:width], height: params[:height], is_cover: params[:is_cover], image_caption: params[:image_caption], image_type: params[:image_type])
-
elsif params[:type] == 'book_cover'
-
params[:images].each do |image|
-
@book.cover_image.attach(data: image)
-
end
-
@book.cover_image.update(index: params[:index], width: params[:width], height: params[:height], is_cover: params[:is_cover], image_caption: params[:image_caption], image_type: params[:image_type])
-
end
-
end
-
-
return success_response(@book)
-
end
-
-
1
def get_user_link
-
@id = validate_json_web_token
-
@account = AccountBlock::Account.find_by(id: @id.id)
-
if @account.present?
-
contribution = BxBlockBook::Contribution.create(user_id: @account.id, unique_identify_id: get_unique_identify_id, shared_link: @account.shared_link)
-
render json: { shared_link: @account.shared_link, unique_identify_id: contribution.unique_identify_id, status: 200 }, status: :ok
-
else
-
render json: { message: "Account not found", status: 404 }, status: :not_found
-
end
-
end
-
-
1
def start_contributing_images
-
@id = validate_json_web_token
-
@account = AccountBlock::Account.find_by(id: @id.id)
-
if @account.present?
-
@contribution = BxBlockBook::Contribution.find_by(shared_link: params[:shared_link])
-
@contribution.friend_id = @account.id
-
@contribution.save
-
if params[:images].present?
-
params[:images].each do |image|
-
@contribution.images.attach(data: image)
-
end
-
end
-
render json: { contribution_data: @contribution, status: 200 }, status: :ok
-
else
-
render json: { message: "Account not found", status: 404 }, status: :not_found
-
end
-
end
-
-
1
def get_contributed_images
-
@id = validate_json_web_token
-
@account = AccountBlock::Account.find_by(id: @id.id)
-
@contributed_images = BxBlockBook::Contribution.where(shared_link: params[:shared_link])
-
render json: {data: BxBlockBook::ContributionSerializer.new(@contributed_images)}
-
end
-
-
1
def delete_contributed_images
-
-
@id = validate_json_web_token
-
@account = AccountBlock::Account.find_by(id: @id.id)
-
-
if @account.present?
-
params[:image_ids].each do |image|
-
attachment = ActiveStorage::Attachment.find_by(id: image).delete
-
end
-
render json: { message: "Attachment destroyed successfully" }, status: 200
-
else
-
render json: { message: "Account not found", status: 404 }, status: :not_found
-
end
-
end
-
-
1
def book_update_new
-
@orders = BxBlockOrderManagement::Order.where(book_id: @book.id)
-
if params[:images].present?
-
images_added = (params[:images].last[:index] + 1) > @book.images.count
-
params[:images].each do |image|
-
@book.images.attach(image["signed_id"])
-
@book.images.last.update(width: image["width"], height: image["height"], index: image["index"], dpi: image["dpi"], image_type: image["image_type"], image_date: image["image_date"], show_date: image["show_date"], image_caption: image["image_caption"], face_position: image["face_position"])
-
end
-
-
@orders.each do |order|
-
family_member = order&.address&.share_with_family_member #boolean values
-
BxBlockOrderManagement::RemoveCoupon.new(order, {}).call if order.coupon_code_id && images_added
-
order.update_additional_page_price(@book&.images&.count&.to_i, family_member)
-
end
-
end
-
if params[:cover_image].present?
-
params[:cover_image].each do |image|
-
@book.cover_image.attach(image["signed_id"])
-
@book.cover_image.update(width: image["width"], height: image["height"], dpi: image["dpi"], image_type: image["image_type"], image_date: image["image_date"], show_date: image["show_date"], image_caption: image["image_caption"])
-
end
-
end
-
return success_response(@book)
-
end
-
-
1
private
-
-
1
def find_book
-
5
@book = Book.find_by(id: params[:id])
-
5
render json: { message: "Invalid Book id" }, status: 422 and return unless @book.present?
-
end
-
-
1
def book_create_params
-
4
params.permit(:month, :year, :spine_title, :cover_image, :from_year, :from_month, :to_year, :to_month)
-
end
-
-
1
def book_update_params
-
1
params.permit(:book_title, :month_range, :month_year, :book_color, :title_layout, :spine_title, :title_color, :logo_color, :cover_type, :cover_image, :from_year, :from_month, :to_year, :to_month, :month, :year)
-
end
-
-
1
def error_response(book)
-
render json: {
-
errors: format_activerecord_errors(book.errors)
-
},
-
status: :unprocessable_entity
-
end
-
-
1
def find_existing_book
-
begin
-
@book = BxBlockBook::Book.find_by(month: params[:month], year: params[:year])
-
rescue ActiveRecord::RecordNotFound => e
-
return render json: {errors: [
-
{ book: 'Book Not Found' },
-
]}, status: 404
-
end
-
end
-
-
1
def success_response(book, status = 200)
-
6
render json: BxBlockBook::BookSerializer.new(book).
-
serializable_hash,
-
status: status
-
end
-
-
1
def check_order
-
@order = BxBlockOrderManagement::Order.find_by(id: params[:id])
-
end
-
-
1
def get_unique_identify_id
-
o = [('a'..'z'), ('A'..'Z'), ('1'..'9')].map(&:to_a).flatten
-
string = (0...5).map { o[rand(o.length)] }.join
-
end
-
-
end
-
end
-
module BxBlockBook
-
class PresignedUploadsController < BxBlockBook::ApplicationController
-
-
def create
-
data = []
-
params[:images].each do |image_params|
-
create_blob(image_params)
-
data << {
-
url: @blob.service_url_for_direct_upload(expires_in: 90.minutes),
-
headers: @blob.service_headers_for_direct_upload,
-
signed_id: @blob.signed_id,
-
index: image_params[:index]
-
}
-
end
-
render json: { data: do_sort(data)}
-
end
-
-
private
-
-
def do_sort(data)
-
data.sort {|first, second| first[:index] <=> second[:index]}
-
end
-
-
def create_blob(image_params)
-
@blob = ActiveStorage::Blob.create_before_direct_upload!(
-
filename: image_params[:filename],
-
byte_size: image_params[:byte_size],
-
checksum: image_params[:checksum],
-
content_type: image_params[:content_type]
-
)
-
end
-
-
def blob_params
-
params.permit(:filename, :byte_size, :checksum, :content_type)
-
end
-
end
-
end
-
module BxBlockBulkUploading
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
# require 'open-uri'
-
# require 'tmpdir'
-
# require 'libreconv'
-
# require 'aws-sdk'
-
# require 'aws-sdk-s3'
-
# require 'base64'
-
-
# module BxBlockBulkUploading
-
class BxBlockBulkUploading::AttachmentsController < ApplicationController
-
# include BuilderJsonWebToken::JsonWebTokenValidation
-
# before_action :validate_json_web_token, :validate_blacklisted_user
-
# before_action :set_account, only: [:create]
-
# before_action :add_allow_credentials_headers, only: [:create]
-
-
# def create
-
# @attachment_serializer = Array.new
-
# params[:data][:attachments].each do |attachment_params|
-
# params[:attachment_data] = attachment_params[1]
-
-
# @attachment = @account.attachments.create(attachments_params)
-
# if params[:attachment_data][:filename].present?
-
# @attachment.attachment_blob.update_attribute(params[:attachment_data][:filename])
-
# end
-
-
# if @attachment.save
-
# obj = Aws::S3::Object.new('secureprinting-bucket', ('a'..'z').to_a.shuffle[0,10].join, "#{Rails.application.credentials.dig(:aws, :access_key_id)}")
-
# if @attachment.attachment.image?
-
# base64_string = Base64.encode64(File.read(params[:attachment_data][:attachment].path))
-
-
# tempfile = Tempfile.new(["#{@attachment&.attachment_blob&.filename.to_s.sub(/\..*/, '')}", ".pdf"], Rails.root.join('tmp'))
-
-
# tempfile.binmode
-
# tempfile.write Base64.decode64(base64_string)
-
# tempfile.close
-
# page_count = 1
-
# if obj.upload_file(tempfile.path, acl:'public-read')
-
# @attachment.update_attributes(pdf_url: obj.public_url, total_attachment_pages: page_count, total_pages: page_count)
-
# else
-
# render json: {errors: [
-
# {user: 'Attachment not uploaded please upload again'},
-
# ]}, status: :unprocessable_entity
-
# end
-
# else
-
# Libreconv.convert("#{params[:attachment_data][:attachment].path}", "public/#{@attachment&.attachment_blob&.filename.to_s.sub(/\..*/, '')}.pdf")
-
# reader = PDF::Reader.new("public/#{@attachment&.attachment_blob&.filename.to_s.sub(/\..*/, '')}.pdf")
-
# page_count = reader.page_count
-
# if obj.upload_file("public/#{@attachment&.attachment_blob&.filename.to_s.sub(/\..*/, '')}.pdf", acl:'public-read')
-
# if @attachment.update_attributes(pdf_url: obj.public_url, total_attachment_pages: page_count, total_pages: page_count)
-
# File.delete(Rails.root + "public/#{@attachment&.attachment_blob&.filename.to_s.sub(/\..*/, '')}.pdf")
-
# end
-
# else
-
# render json: {errors: [
-
# {user: 'Attachment not uploaded please upload again'},
-
# ]}, status: :unprocessable_entity
-
# end
-
# end
-
# @attachment_serializer << @attachment if @attachment.persisted?
-
# else
-
# render json: {errors: format_activerecord_errors(@attachment.errors)},
-
# status: :unprocessable_entity
-
# end
-
# end
-
-
# if @attachment_serializer.present?
-
# render json: AttachmentSerializer.new(@attachment_serializer, meta: {
-
# message: "Attachment Created Successfully"
-
# }).serializable_hash, status: :created
-
# else
-
# render json: {errors: format_activerecord_errors(@attachment.errors)},
-
# status: :unprocessable_entity
-
# end
-
# end
-
-
# def destroy
-
# account = AccountBlock::Account.find @token.id if @token.id.present?
-
# if account.present?
-
# attachment = account.attachments.find params[:id]
-
# if attachment.attachment.attached?
-
# attachment.update_attributes(:is_expired => true)
-
# attachment.destroy
-
# if account.attachments.present?
-
# attachments = Array.new
-
# account.attachments.each do |attachment|
-
# if attachment&.attachment&.attached?
-
# attachments << attachment
-
# end
-
# end
-
# end
-
# if attachments.present?
-
# render json: {meta: [{message: 'Attachment Deleted Successfully'},
-
# ]}, status: :ok
-
# else
-
# render json: {meta: [
-
# {message: 'Attachment deleted successfully and no more attachments'},
-
# ]}, status: :ok
-
# end
-
# else
-
# render json: {errors: [
-
# {user: 'Attachment not found'},
-
# ]}, status: :unprocessable_entity
-
# end
-
# end
-
# end
-
-
# private
-
-
# def set_account
-
# if params[:data].present?
-
# @account = AccountBlock::Account.find params[:data][:account_id]
-
# end
-
# end
-
# def attachments_params
-
# params.require(:attachment_data).permit(:colour, :layout, :page_size, :pdf_url, :scale,
-
# :print_sides,:print_pages_from, :print_pages_to,
-
# :total_attachment_pages, :total_pages, :is_expired,
-
# :attachment)
-
# end
-
-
# def add_allow_credentials_headers
-
# headers['Access-Control-Allow-Origin'] = '*'
-
# headers['Access-Control-Allow-Methods'] = 'POST, PUT, DELETE, GET, OPTIONS'
-
# headers['Access-Control-Request-Method'] = '*'
-
# headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'
-
# end
-
-
# def format_activerecord_errors(errors)
-
# result = []
-
# errors.each do |attribute, error|
-
# result << { attribute => error }
-
# end
-
# result
-
# end
-
end
-
# end
-
module BxBlockCalendar
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
module BxBlockCalendar
-
class AvailabilitiesController < ApplicationController
-
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :check_user_role, only: %i(update_availability_time)
-
before_action :get_service_provider, only: %i(get_booked_time_slots)
-
-
def update_availability_time
-
slot = BxBlockAppointmentManagement::Availability.new(
-
slot_detail.merge({ service_provider_id: @service_provider.id })
-
)
-
if slot.save
-
render json: BxBlockCalendar::AvailabilitySerializer.new(slot, meta: {
-
message: 'Your slot created for the day'
-
}).serializable_hash, status: :created
-
else
-
render json: { errors: format_activerecord_errors(slot.errors) },
-
status: :unprocessable_entity
-
end
-
end
-
-
private
-
def slot_detail
-
params.require(:availability).permit(
-
:availability_date, :start_time, :end_time, :unavailable_start_time, :unavailable_end_time
-
)
-
end
-
-
def check_user_role
-
@service_provider = AccountBlock::Account.find_by(id: @token.id)
-
render json: {
-
errors: 'Permission denied'
-
} and return unless is_merchant?#@service_provider.is_merchant?
-
end
-
-
def format_activerecord_errors(errors)
-
result = []
-
errors.each do |attribute, error|
-
result << { attribute => error }
-
end
-
result
-
end
-
-
def is_merchant?
-
role = BxBlockRolesPermissions::Role.find_by(id: @service_provider.role_id)
-
return false unless role
-
role.name == 'Merchant'
-
end
-
end
-
end
-
module BxBlockCalendar
-
class BookedSlotsController < ApplicationController
-
-
def index
-
unless params[:service_provider_id].blank? || params[:date].blank?
-
booked_slots = BxBlockAppointmentManagement::BookedSlot.where(
-
service_provider_id: params[:service_provider_id],
-
booking_date: params[:date]
-
)
-
render json: BxBlockCalendar::BookedSlotSerializer.new(booked_slots)
-
else
-
render json: {errors: [
-
{availability: 'Date or Service provider Account id is empty'},
-
]}, status: :unprocessable_entity
-
end
-
end
-
end
-
end
-
module BxBlockCatalogue
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
module BxBlockCatalogue
-
class BrandsController < ApplicationController
-
def create
-
brand = Brand.new(name: params[:name])
-
save_result = brand.save
-
-
if save_result
-
render json: BrandSerializer.new(brand).serializable_hash,
-
status: :created
-
else
-
render json: ErrorSerializer.new(brand).serializable_hash,
-
status: :unprocessable_entity
-
end
-
end
-
-
def index
-
serializer = BrandSerializer.new(Brand.all)
-
-
render json: serializer, status: :ok
-
end
-
end
-
end
-
module BxBlockCatalogue
-
class CataloguesController < ApplicationController
-
before_action :load_catalogue, only: %i[show update destroy]
-
-
def create
-
catalogue = Catalogue.new(catalogue_params)
-
save_result = catalogue.save
-
-
if save_result
-
process_images(catalogue, params[:images])
-
-
catalogue.tags << Tag.where(id: params[:tags_id])
-
-
process_variants_images(catalogue)
-
-
render json: CatalogueSerializer.new(catalogue, serialization_options)
-
.serializable_hash,
-
status: :created
-
else
-
render json: ErrorSerializer.new(catalogue).serializable_hash,
-
status: :unprocessable_entity
-
end
-
end
-
-
def show
-
return if @catalogue.nil?
-
-
render json: CatalogueSerializer.new(@catalogue, serialization_options)
-
.serializable_hash,
-
status: :ok
-
end
-
-
def index
-
catalogues = Catalogue.all
-
serializer = CatalogueSerializer.new(catalogues, serialization_options)
-
-
render json: serializer, status: :ok
-
end
-
-
def destroy
-
return if @catalogue.nil?
-
-
if @catalogue.destroy
-
render json: { success: true }, status: :ok
-
else
-
render json: ErrorSerializer.new(@catalogue).serializable_hash,
-
status: :unprocessable_entity
-
end
-
end
-
-
def update
-
return if @catalogue.nil?
-
-
update_result = @catalogue.update(catalogue_params)
-
-
update_tags
-
process_images(@catalogue, params[:images])
-
process_variants_images(@catalogue)
-
-
if update_result
-
render json: CatalogueSerializer.new(@catalogue, serialization_options)
-
.serializable_hash,
-
status: :ok
-
else
-
render json: ErrorSerializer.new(@catalogue).serializable_hash,
-
status: :unprocessable_entity
-
end
-
end
-
-
private
-
-
def load_catalogue
-
@catalogue = Catalogue.find_by(id: params[:id])
-
-
if @catalogue.nil?
-
render json: {
-
message: "Catalogue with id #{params[:id]} doesn't exists"
-
}, status: :not_found
-
end
-
end
-
-
def catalogue_params
-
params.permit(:category_id, :sub_category_id, :brand_id,
-
:name, :sku, :description, :manufacture_date, :length,
-
:breadth, :height, :stock_qty, :availability, :weight,
-
:price, :recommended, :on_sale, :sale_price, :discount,
-
catalogue_variants_attributes:
-
%i[id catalogue_variant_color_id
-
catalogue_variant_size_id price stock_qty
-
on_sale sale_price discount_price length breadth
-
height _destroy])
-
-
-
end
-
-
def update_tags
-
tags = @catalogue.tags
-
-
existing_tags_id = tags.map(&:id)
-
params_tags = params[:tags_id] || []
-
-
remove_ids = existing_tags_id - params_tags
-
if remove_ids.size.positive?
-
@catalogue.tags.delete(Tag.where(id: remove_ids))
-
end
-
-
add_ids = params_tags - existing_tags_id
-
if add_ids.size.positive?
-
@catalogue.tags << Tag.where(id: add_ids)
-
end
-
end
-
-
def process_images(imagable, images_params)
-
return unless images_params.present?
-
-
images_to_attach = []
-
images_to_remove = []
-
-
images_params.each do |image_data|
-
if image_data[:id].present? &&
-
(image_data[:remove].present? || image_data[:data].present?)
-
images_to_remove << image_data[:id]
-
end
-
-
if image_data[:data]
-
images_to_attach.push(
-
io: StringIO.new(Base64.decode64(image_data[:data])),
-
content_type: image_data[:content_type],
-
filename: image_data[:filename]
-
)
-
end
-
end
-
-
imagable.images.where(id: images_to_remove).purge if
-
images_to_remove.size.positive?
-
imagable.images.attach(images_to_attach) if
-
images_to_attach.size.positive?
-
end
-
-
def process_variants_images(catalogue)
-
variants = params[:catalogue_variants_attributes]
-
-
return unless variants.present?
-
-
variants.each_with_index do |v, index|
-
next unless v[:images].present?
-
-
process_images(catalogue.catalogue_variants[index], v[:images])
-
end
-
end
-
-
def serialization_options
-
{ params: { host: request.protocol + request.host_with_port } }
-
end
-
end
-
end
-
-
module BxBlockCatalogue
-
class CataloguesVariantsColorsController < ApplicationController
-
def create
-
colors = CatalogueVariantColor.new(name: params[:name])
-
save_result = colors.save
-
-
if save_result
-
render json: CatalogueVariantColorSerializer.new(colors)
-
.serializable_hash,
-
status: :created
-
else
-
render json: ErrorSerializer.new(colors).serializable_hash,
-
status: :unprocessable_entity
-
end
-
end
-
-
def index
-
serializer = CatalogueVariantColorSerializer.new(
-
CatalogueVariantColor.all
-
)
-
-
render json: serializer, status: :ok
-
end
-
end
-
end
-
module BxBlockCatalogue
-
class CataloguesVariantsController < ApplicationController
-
def create
-
variant = CatalogueVariant.new(variants_params)
-
save_result = variant.save
-
-
if save_result
-
render json: CatalogueVariantSerializer.new(
-
variant, serialization_options
-
).serializable_hash,
-
status: :created
-
else
-
render json: ErrorSerializer.new(variant).serializable_hash,
-
status: :unprocessable_entity
-
end
-
end
-
-
def index
-
serializer = CatalogueVariantSerializer.new(
-
CatalogueVariant.all, serialization_options
-
)
-
-
render json: serializer, status: :ok
-
end
-
-
def variants_params
-
params.permit(:catalogue_id, :catalogue_variant_color_id,
-
:catalogue_variant_size_id, :price, :stock_qty, :on_sale,
-
:sale_price, :discount_price, :decimal, :length, :breadth,
-
:height, :images)
-
end
-
-
def serialization_options
-
{ params: { host: request.protocol + request.host_with_port } }
-
end
-
end
-
end
-
-
module BxBlockCatalogue
-
class CataloguesVariantsSizesController < ApplicationController
-
def create
-
sizes = CatalogueVariantSize.new(name: params[:name])
-
save_result = sizes.save
-
-
if save_result
-
render json: CatalogueVariantSizeSerializer.new(sizes)
-
.serializable_hash,
-
status: :created
-
else
-
render json: ErrorSerializer.new(sizes).serializable_hash,
-
status: :unprocessable_entity
-
end
-
end
-
-
def index
-
serializer = CatalogueVariantSizeSerializer.new(CatalogueVariantSize.all)
-
-
render json: serializer, status: :ok
-
end
-
end
-
end
-
module BxBlockCatalogue
-
class ReviewsController < ApplicationController
-
def create
-
review = Review.new(
-
catalogue_id: params[:catalogue_id],
-
rating: params[:rating],
-
comment: params[:comment]
-
)
-
save_result = review.save
-
-
if save_result
-
render json: ReviewSerializer.new(review).serializable_hash,
-
status: :created
-
else
-
render json: ErrorSerializer.new(review).serializable_hash,
-
status: :unprocessable_entity
-
end
-
end
-
-
def index
-
serializer = ReviewSerializer.new(Review.all)
-
-
render json: serializer, status: :ok
-
end
-
end
-
end
-
module BxBlockCatalogue
-
class TagsController < ApplicationController
-
def create
-
tag = Tag.new(name: params[:name])
-
save_result = tag.save
-
-
if save_result
-
render json: TagSerializer.new(tag).serializable_hash,
-
status: :ok
-
else
-
render json: ErrorSerializer.new(tag).serializable_hash,
-
status: :unprocessable_entity
-
end
-
end
-
-
def index
-
serializer = TagSerializer.new(Tag.all)
-
-
render json: serializer, status: :ok
-
end
-
end
-
end
-
module BxBlockCategories
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
-
def current_user
-
return unless @token
-
@current_user ||= AccountBlock::Account.find(@token.id)
-
end
-
end
-
end
-
module BxBlockCategories
-
class CategoriesController < ApplicationController
-
before_action :load_category, only: [:show, :update, :destroy]
-
-
def create
-
if params[:categories].blank? || params[:categories].size.zero?
-
raise 'Wrong input data'
-
end
-
-
categories_to_create = params[:categories].map do |x|
-
x.permit(:name).to_h
-
end
-
-
ActiveRecord::Base.transaction do
-
@categories = Category.create!(categories_to_create)
-
end
-
-
render json: CategorySerializer.new(@categories, serialization_options)
-
.serializable_hash,
-
status: :created
-
end
-
-
def show
-
return if @category.nil?
-
-
render json: CategorySerializer.new(@category, serialization_options)
-
.serializable_hash,
-
status: :ok
-
end
-
-
def index
-
serializer = if params[:sub_category_id].present?
-
categories = SubCategory.find(params[:sub_category_id])
-
.categories
-
CategorySerializer.new(categories)
-
else
-
CategorySerializer.new(Category.all, serialization_options)
-
end
-
-
render json: serializer, status: :ok
-
end
-
-
def destroy
-
return if @category.nil?
-
-
begin
-
if @category.destroy
-
remove_not_used_subcategories
-
-
render json: { success: true }, status: :ok
-
end
-
rescue ActiveRecord::InvalidForeignKey
-
message = "Record can't be deleted due to reference to a catalogue " \
-
"record"
-
-
render json: {
-
error: { message: message }
-
}, status: :internal_server_error
-
end
-
end
-
-
def update
-
return if @category.nil?
-
-
update_result = @category.update(name: params[:category_name])
-
-
if update_result
-
render json: CategorySerializer.new(@category).serializable_hash,
-
status: :ok
-
else
-
render json: ErrorSerializer.new(@category).serializable_hash,
-
status: :unprocessable_entity
-
end
-
end
-
-
def update_user_categories
-
if current_user.update(category_ids: params[:categories_ids])
-
serializer = CategorySerializer.new(current_user.categories)
-
serialized = serializer.serializable_hash
-
render json: serialized
-
else
-
render json: {errors: current_user.errors, status: :unprocessable_entity}
-
end
-
end
-
-
private
-
-
def load_category
-
@category = Category.find_by(id: params[:id])
-
-
if @category.nil?
-
render json: {
-
message: "Category with id #{params[:id]} doesn't exists"
-
}, status: :not_found
-
end
-
end
-
-
def serialization_options
-
options = {}
-
options[:params] = { sub_categories: true }
-
options
-
end
-
-
def remove_not_used_subcategories
-
sql = "delete from sub_categories sc where sc.id in (
-
select sc.id from sub_categories sc
-
left join categories_sub_categories csc on
-
sc.id = csc.sub_category_id
-
where csc.sub_category_id is null
-
)"
-
ActiveRecord::Base.connection.execute(sql)
-
end
-
end
-
end
-
-
module BxBlockCategories
-
class CtaController < ApplicationController
-
before_action :assign_cta, only: [:index]
-
skip_before_action :validate_json_web_token, only: [:index]
-
-
def index
-
filter_cta
-
@ctas = @ctas.page(params[:page]).per(params[:per_page])
-
render json: CtaSerializer.new(@ctas).serializable_hash, status: :ok
-
end
-
-
private
-
-
def assign_cta
-
@ctas = Cta.includes(:category)
-
end
-
-
def filter_cta
-
params.each do |key, value|
-
case key
-
when 'category'
-
@ctas = @ctas.where(categories: {id: value})
-
when 'visible_on_details_page'
-
@ctas = @ctas.where(visible_on_details_page: true)
-
when 'visible_on_home_page'
-
@ctas = @ctas.where(visible_on_home_page: true)
-
end
-
end
-
end
-
end
-
end
-
module BxBlockCategories
-
class SubCategoriesController < ApplicationController
-
before_action :load_sub_category, only: [:show, :update, :destroy]
-
-
def create
-
if params[:sub_category].blank? || params[:sub_category][:name].blank?
-
raise 'Wrong input data'
-
end
-
-
sub_category = SubCategory.new(name: params[:sub_category][:name])
-
if params[:parent_categories].present?
-
sub_category.categories << Category.where(
-
id: params[:parent_categories]
-
)
-
end
-
if sub_category.valid?
-
sub_category.save
-
-
render json: SubCategorySerializer.new(
-
sub_category,
-
serialization_options
-
).serializable_hash,
-
status: :created
-
else
-
render json: ErrorSerializer.new(sub_category).serializable_hash,
-
status: :unprocessable_entity
-
end
-
end
-
-
def show
-
return if @sub_category.nil?
-
-
render json: SubCategorySerializer.new(@sub_category).serializable_hash,
-
status: :ok
-
end
-
-
def index
-
serializer = if params[:category_id].present?
-
sub_categories = Category.find(params[:category_id])
-
.sub_categories
-
SubCategorySerializer.new(sub_categories)
-
else
-
SubCategorySerializer.new(
-
SubCategory.all,
-
serialization_options
-
)
-
end
-
-
render json: serializer, status: :ok
-
end
-
-
def destroy
-
return if @sub_category.nil?
-
-
begin
-
if @sub_category.destroy
-
render json: { success: true }, status: :ok
-
end
-
rescue ActiveRecord::InvalidForeignKey
-
message = "Record can't be deleted due to reference to catalogue"
-
-
render json: {
-
error: { message: message }
-
}, status: :internal_server_error
-
end
-
-
end
-
-
def update
-
return if @sub_category.nil?
-
-
update_result = @sub_category.update(name: params[:sub_category][:name])
-
-
if update_result
-
render json: SubCategorySerializer.new(@sub_category).serializable_hash,
-
status: :ok
-
else
-
render json: ErrorSerializer.new(@sub_category).serializable_hash,
-
status: :unprocessable_entity
-
end
-
end
-
-
def update_user_sub_categories
-
if current_user.update(sub_category_ids: params[:sub_categories_ids])
-
serializer = SubCategorySerializer.new(current_user.sub_categories)
-
serialized = serializer.serializable_hash
-
render json: serialized
-
else
-
render json: {errors: current_user.errors, status: :unprocessable_entity}
-
end
-
end
-
-
private
-
-
def load_sub_category
-
@sub_category = SubCategory.find_by(id: params[:id])
-
-
if @sub_category.nil?
-
render json: {
-
message: "SubCategory with id #{params[:id]} doesn't exists"
-
}, status: :not_found
-
end
-
end
-
-
def serialization_options
-
options = {}
-
options[:params] = { categories: true }
-
options
-
end
-
end
-
end
-
-
module BxBlockCfanimationsandtransition2
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
module BxBlockCfgooglephotosintegration2
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
module BxBlockCfinterfaceforbookpreview2
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
module BxBlockCfshiprocketintegration2
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class ApplicationController < BuilderBase::ApplicationController
-
include JSONAPI::Deserialization
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
around_action :set_locale
-
-
before_action :update_current_user
-
-
private
-
-
def not_found
-
render :json => {'errors' => [app_t('controllers.application.errors.record_not_found')]}, :status => :not_found
-
end
-
-
def assign_json_web_token
-
token = request.headers[:token] || params[:token]
-
begin
-
@token = BuilderJsonWebToken::JsonWebToken.decode(token)
-
rescue *ERROR_CLASSES => exception
-
end
-
end
-
-
def current_user
-
return unless @token
-
account_id = @token.id
-
account = AccountBlock::Account.find(account_id)
-
end
-
-
def set_locale
-
lang = params[:language] || I18n.default_locale
-
Globalize.with_locale(lang) do
-
yield
-
end
-
end
-
-
def format_activerecord_errors(errors)
-
[{ error: errors.full_messages.first }]
-
end
-
-
def app_t(key)
-
BxBlockLanguageOptions::ApplicationMessage.translation_message(key)
-
end
-
-
def update_current_user
-
current_user.update(last_visit_at: Time.now) if current_user.present?
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class AuthorsController < ApplicationController
-
skip_before_action :validate_json_web_token, only: [:show, :index]
-
-
def show
-
@author = BxBlockContentManagement::Author.find_by(id: params[:id])
-
render json: BxBlockContentManagement::AuthorSerializer.new(@author).serializable_hash, status: :ok
-
end
-
-
def index
-
content_types = BxBlockContentManagement::Author.all.page(params[:page]).per(params[:per_page])
-
render json: BxBlockContentManagement::AuthorSerializer.new(content_types).serializable_hash, status: :ok
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class BookmarksController < ApplicationController
-
before_action :validate_json_web_token, only: [:create, :destroy, :index]
-
-
def create
-
bookmark = current_user.bookmarks.new(content_id: params[:content_id])
-
-
if bookmark.save
-
render json: BxBlockContentManagement::BookmarkSerializer.new(bookmark).serializable_hash,
-
status: :created
-
else
-
render json: BxBlockContentManagement::ErrorSerializer.new(bookmark).serializable_hash,
-
status: :unprocessable_entity
-
end
-
end
-
-
def index
-
contents = current_user.content_followings
-
render json: BxBlockContentManagement::ContentSerializer.new(contents, serialization_options).serializable_hash,
-
status: :ok
-
end
-
-
def destroy
-
follow = current_user.bookmarks.find(params[:id])
-
if follow.destroy
-
render json: { success: true }, status: :ok
-
else
-
render json: BxBlockContentManagement::ErrorSerializer.new(follow).serializable_hash,
-
status: :unprocessable_entity
-
end
-
end
-
-
private
-
def serialization_options
-
options = {}
-
options[:params] = { current_user_id: current_user&.id}
-
options
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class ContentProvidersController < ApplicationController
-
skip_before_action :validate_json_web_token, only: [:index]
-
end
-
end
-
module BxBlockContentManagement
-
class ContentTypesController < ApplicationController
-
skip_before_action :validate_json_web_token, only: [:index]
-
-
def index
-
content_types = BxBlockContentManagement::ContentType.all.order(:rank).page(params[:page]).per(params[:per_page])
-
render json: BxBlockContentManagement::ContentTypeSerializer.new(content_types).serializable_hash, status: :ok
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class ContentsController < ApplicationController
-
before_action :assign_contents, only: [:index, :show]
-
skip_before_action :validate_json_web_token, only: [:get_content_detail, :index, :show,
-
:reindex_contents, :run_seeds]
-
before_action :authorize_request, only: [:reindex_contents, :run_seeds]
-
before_action :set_category, :set_sub_category, :set_content_type, :set_language, only: [:contents]
-
-
def get_content_detail
-
@content_type_id = params[:id]
-
content_type_obj = BxBlockContentManagement::ContentType.find_by(id: params["id"])
-
@content_type = content_type_obj&.type
-
@content_name = content_type_obj&.name
-
-
if params[:content_id].present?
-
@contentable = BxBlockContentManagement::Content.find_by(id: params[:content_id])&.contentable
-
end
-
if @content_type.present?
-
render 'rails_admin/application/form_template'
-
end
-
end
-
-
def contents
-
tags = params[:tag_list]
-
content = BxBlockContentManagement::CreateContentService.create_content(
-
@content_type, content_params, @sub_category, @language, @category, tags
-
)
-
if content.present? && content[:errors].present?
-
render json: {errors: content[:errors], status: 404}
-
else
-
render json: {content: ContentSerializer.new(content).serializable_hash, success: true,
-
message: "Content created successfully!"}
-
end
-
end
-
-
def index
-
filter_content
-
if params[:search].present?
-
@contents = Content.search(
-
params[:search], misspellings: true, page: params[:page], per_page: params[:per_page],
-
where: { id: @contents.ids }
-
)
-
else
-
@contents = @contents.page(params[:page]).per(params[:per_page])
-
end
-
render json: ContentSerializer.new(@contents, serialization_options).serializable_hash, status: :ok
-
end
-
-
def show
-
@content = @contents.find(params[:id])
-
@content.update(view_count: @content.view_count + 1)
-
render json: ContentSerializer.new(@content).serializable_hash, status: :ok
-
end
-
-
def reindex_contents
-
BxBlockContentManagement::Content.reindex
-
render json: { message: "Content reindexed Successfully!" }
-
end
-
-
def run_seeds
-
load Rails.root + "db/seeds.rb"
-
render json: { message: "Successfully! run seeds" }
-
end
-
-
private
-
-
def assign_contents
-
@contents = BxBlockContentManagement::Content.published.includes(
-
:category, :sub_category, :content_type, :language
-
)
-
end
-
-
def set_category
-
@category = BxBlockCategories::Category.find_by(id: params[:category_id])
-
unless @category.present?
-
return render json: {error: "can't find category with this id '#{params[:category_id]}'"}
-
end
-
end
-
-
def content_params
-
params.permit(:category_id, :sub_category_id, :language_id, :author_id, :headline,
-
:description, :feature_article, :feature_video, :searchable_text,
-
:content_type_id, :archived, :status, :publish_date, :tag_list,
-
:heading, :content, :hyperlink, :affiliation, :separate_section,
-
images_attributes: [:image], videos_attributes: [:video],
-
image_attributes: [:image], audio_attributes: [:audio],
-
pdfs_attributes: [:pdf], video_attributes: [:video])
-
end
-
-
def set_sub_category
-
@sub_category = BxBlockCategories::SubCategory.find_by(id: params[:sub_category_id])
-
unless @sub_category.present?
-
return render json: {error: "can't find sub category with this id '#{params[:sub_category_id]}'"}
-
end
-
end
-
-
def set_content_type
-
@content_type = BxBlockContentManagement::ContentType.find_by(id: params[:content_type_id])
-
unless @content_type.present?
-
return render json: {error: "can't find content type with this id '#{params[:content_type_id]}'"}
-
end
-
end
-
-
def set_language
-
@language = BxBlockLanguageOptions::Language.find_by(id: params[:language_id])
-
unless @language.present?
-
return render json: {error: "can't find language with this id '#{params[:language_id]}'"}
-
end
-
end
-
-
def filter_content
-
params.each do |key, value|
-
case key
-
when 'content_type'
-
@contents = @contents.where(content_types: {id: value})
-
when 'category'
-
@contents = @contents.where(categories: {id: value})
-
when 'date'
-
@contents = @contents.where(
-
"(publish_date < ?) and (publish_date > ?)", value["to"].to_datetime, value["from"].to_datetime
-
)
-
when 'feature_article'
-
@contents = @contents.where(feature_article: value)
-
when 'feature_video'
-
@contents = @contents.where(feature_video: value)
-
when 'content_language'
-
@contents = @contents.where(languages: {id: value})
-
when 'sub_category'
-
@contents = @contents.where(sub_categories: {id: value})
-
when 'tag'
-
@contents = @contents.tagged_with(value, any: true)
-
when 'content_provider'
-
@contents = @contents.where(admin_user_id: value)
-
end
-
end
-
end
-
-
def serialization_options
-
assign_json_web_token
-
options = {}
-
options[:params] = { current_user_id: (current_user&.id)}
-
options
-
end
-
-
def authorize_request
-
return render json: {data: [
-
{account: "Please use correct api_access_key."},
-
]}, status: 401 unless Rails.application.secrets.api_access_key == params[:api_access_key]
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class ExamsController < ApplicationController
-
before_action :assign_exams, only: [:index, :show]
-
skip_before_action :validate_json_web_token, only: [:index, :show]
-
-
def index
-
filter_exam
-
render json: ExamSerializer.new(@exams).serializable_hash, status: :ok
-
end
-
-
def show
-
@exam = @exams.find_by(id: params[:id])
-
render json: ExamSerializer.new(@exam).serializable_hash, status: :ok
-
end
-
-
private
-
-
def filter_exam
-
params.each do |key, value|
-
case key
-
when 'date'
-
@exams = @exams.where(:to => value["to"].to_date..value["from"].to_date).or(
-
@exams.where(:from => value["to"].to_date..value["from"].to_date)
-
)
-
end
-
end
-
end
-
-
def assign_exams
-
@exams = BxBlockContentManagement::Exam.all
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class FollowsController < ApplicationController
-
before_action :validate_json_web_token, only: [:create, :destroy, :index, :followers_content]
-
-
def create
-
follow = current_user.followers.new(content_provider_id: params[:content_provider_id])
-
-
if follow.save
-
render json: FollowSerializer.new(follow).serializable_hash,
-
status: :created
-
else
-
render json: ErrorSerializer.new(follow).serializable_hash,
-
status: :unprocessable_entity
-
end
-
end
-
-
def index
-
render json: BxBlockContentManagement::ContentProviderSerializer.new(
-
current_user.content_provider_followings, serialization_options
-
).serializable_hash, status: :ok
-
end
-
-
def destroy
-
follow = current_user.followers.find(params[:id])
-
if follow.destroy
-
render json: { success: true }, status: :ok
-
else
-
render json: ErrorSerializer.new(follow).serializable_hash,
-
status: :unprocessable_entity
-
end
-
end
-
-
private
-
def serialization_options
-
options = {}
-
options[:params] = { current_user_id: current_user&.id}
-
options
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class TagsController < ApplicationController
-
skip_before_action :validate_json_web_token, only: [:index]
-
-
def index
-
tags = ActsAsTaggableOn::Tag.all.page(params[:page]).per(params[:per_page])
-
render json: TagSerializer.new(tags).serializable_hash, status: :ok
-
end
-
end
-
end
-
module BxBlockCors
-
class ApplicationController < BuilderBase::ApplicationController
-
# protect_from_forgery with: :exception
-
end
-
end
-
module BxBlockCouponCg
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
module BxBlockCouponCg
-
class CouponCodeGeneratorController < ApplicationController
-
before_action :load_coupon, only: [:show, :update, :destroy]
-
-
def create
-
coupon = CouponCode.new(coupon_params)
-
save_result = coupon.save
-
-
if save_result
-
render json: CouponCodeSerializer.new(coupon).serializable_hash,
-
status: :created
-
else
-
render json: ErrorSerializer.new(coupon).serializable_hash,
-
status: :unprocessable_entity
-
end
-
end
-
-
def show
-
return if @coupon.nil?
-
-
render json: CouponCodeSerializer.new(@coupon).serializable_hash,
-
status: :ok
-
end
-
-
def index
-
coupons = CouponCode.all
-
serializer = CouponCodeSerializer.new(coupons)
-
-
render json: serializer, status: :ok
-
end
-
-
def destroy
-
return if @coupon.nil?
-
-
if @coupon.destroy
-
render json: {}, status: :ok
-
else
-
render json: ErrorSerializer.new(@coupon).serializable_hash,
-
status: :unprocessable_entity
-
end
-
end
-
-
def update
-
return if @coupon.nil?
-
-
update_result = @coupon.update(coupon_params)
-
-
if update_result
-
render json: CouponCodeSerializer.new(@coupon).serializable_hash,
-
status: :ok
-
else
-
render json: ErrorSerializer.new(@coupon).serializable_hash,
-
status: :unprocessable_entity
-
end
-
end
-
-
private
-
-
def load_coupon
-
@coupon = CouponCode.find_by(id: params[:id])
-
-
if @coupon.nil?
-
render json: {
-
message: "Coupon with id #{params[:id]} doesn't exists"
-
}, status: :not_found
-
end
-
end
-
-
def coupon_params
-
params.require(:data).permit(:title, :description, :code, :discount_type,
-
:discount, :valid_from, :valid_to, :min_cart_value,
-
:max_cart_value)
-
end
-
end
-
end
-
-
module BxBlockCoupons
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
module BxBlockCoupons
-
class CouponsController < ApplicationController
-
def check_applicability
-
discount = BxBlockCoupons::CouponApplicabilityCommand.check(
-
@token.id, jsonapi_deserialize(params)
-
)
-
case discount.first
-
when :unprocessable_entity
-
render json: {
-
errors: discount.second,
-
}, status: :unprocessable_entity
-
when :coupon_applied
-
render json: {
-
meta: {
-
discount: discount.second,
-
message: "Coupon is applicable",
-
coupon_id: discount.third
-
}
-
}
-
end
-
end
-
-
def get_refferal_coupon
-
refferal_coupon = RefferalCoupon.last
-
if refferal_coupon.present?
-
render json: {meta: {refferal_coupon: refferal_coupon, message: "Refferal Coupon" }}
-
else
-
render json: { errors: ["Refferal Coupon not found."] }, status: :unprocessable_entity
-
end
-
end
-
end
-
end
-
module BxBlockCoupons
-
class SpecialOffersController < ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
before_action :validate_json_web_token
-
-
def show
-
special_offer = BxBlockCoupons::ComboOffer.find(params[:id])
-
render json: BxBlockCoupons::SpecialOfferSerializer.new(
-
special_offer
-
).serializable_hash, status: :ok
-
end
-
-
def get_service_provider
-
render json: {
-
errors: 'Select any date to to get availability'
-
} and return unless params[:date].present?
-
service_provider = BxBlockAppointmentManagement::Availability.where(
-
availability_date: Date.parse(params[:date]).strftime('%d/%m/%y')
-
).order(:available_slots_count)&.first&.service_provider
-
render json: {
-
errors: "No service provider is available for date:#{params[:date]}"
-
} and return unless service_provider.present?
-
render json: AccountBlock::AccountSerializer.new(
-
service_provider
-
).serializable_hash, status: :ok
-
end
-
end
-
end
-
module BxBlockCustomForm
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
-
def current_user
-
@current_user ||= AccountBlock::Account.find(@token.id) if @token.present?
-
end
-
end
-
end
-
module BxBlockCustomForm
-
class SellerAccountsController < ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
skip_before_action :validate_json_web_token, :only => [:index]
-
-
def index
-
if params[:search_term].present?
-
@seller = SellerAccount.where(
-
"firm_name LIKE ?", "%#{params[:search_term]}%"
-
)
-
render json: {seller: @seller, full_messages: "Successfully Loaded"}
-
elsif params[:lat].present? && params[:long].present?
-
@seller_whole = SellerAccount.within(
-
2,
-
:units => :kms,
-
:origin => "#{params[:lat]}, #{params[:long]}"
-
)
-
@seller_retail = SellerAccount.within(
-
2,
-
:units => :kms,
-
:origin => "#{params[:lat]}, #{params[:long]}"
-
)
-
render json: {
-
seller_whole: @seller_whole,
-
seller_retail: @seller_retail,
-
message: "Successfully Loaded"
-
}
-
else
-
@seller = SellerAccount.all
-
render json: {seller: @seller, full_messages: "Successfully Loaded"}
-
end
-
end
-
-
def create
-
@seller_account = SellerAccount.new(
-
seller_account_params.merge( { account_id: current_user.id} )
-
)
-
if @seller_account.save
-
render json: SellerAccountSerializer.new(@seller_account
-
).serializable_hash, status: :created
-
else
-
render json: {
-
errors: format_activerecord_errors(@seller_account.errors)
-
}, status: :unprocessable_entity
-
end
-
end
-
-
def show
-
seller_account = SellerAccount.find_by(account_id: current_user.id)
-
render json: SellerAccountSerializer.new(seller_account).as_json
-
end
-
-
def update
-
seller_account = SellerAccount.find_by(account_id: current_user.id)
-
if seller_account.update(seller_account_params)
-
serializer = SellerAccountSerializer.new(seller_account)
-
render :json => serializer.as_json,
-
:status => :ok
-
else
-
render :json => {:errors => seller_account.errors.full_messages},
-
:status => status
-
end
-
end
-
-
private
-
-
def seller_account_params
-
params.require(:seller_account).permit(:firm_name,
-
:full_phone_number,
-
:location,
-
:country_code,
-
:phone_number,
-
:gstin_number,
-
:wholesaler,
-
:retailer,
-
:manufacturer,
-
:hallmarking_center,
-
:buy_gold,
-
:buy_silver,
-
:sell_gold,
-
:sell_silver,
-
:activated,
-
:lat,
-
:long)
-
end
-
end
-
end
-
module BxBlockCustomUserSubs
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
-
def current_user
-
@current_user ||= AccountBlock::Account.find(@token.id) if @token.present?
-
end
-
end
-
end
-
module BxBlockCustomUserSubs
-
class SubscriptionsController < ApplicationController
-
-
def index
-
subscriptions = BxBlockCustomUserSubs::Subscription.all
-
render json: BxBlockCustomUserSubs::SubscriptionSerializer.new(subscriptions, params: {user: current_user}).serializable_hash
-
end
-
-
end
-
end
-
module BxBlockCustomUserSubs
-
class UserSubscriptionsController < ApplicationController
-
-
# def index
-
# render json: BxBlockCustomUserSubs::SubscriptionSerializer.new(user_subscriptions, params: {user: current_user}).serializable_hash
-
# end
-
-
# def show
-
# subscription = user_subscriptions.find(params[:id])
-
# render json: BxBlockCustomUserSubs::SubscriptionSerializer.new(subscription, params: {user: current_user}).serializable_hash
-
# end
-
-
def create
-
user_subscription = BxBlockCustomUserSubs::UserSubscription.create(subscription_id: params[:id], account_id: current_user.id)
-
subscription = user_subscription.subscription
-
render json: BxBlockCustomUserSubs::SubscriptionSerializer.new(subscription, params: {user: current_user}).serializable_hash
-
end
-
-
private
-
-
# def user_subscriptions
-
# BxBlockCustomUserSubs::Subscription.joins(:user_subscription).where('user_subscription.account_id = ?', current_user.id)
-
# end
-
-
end
-
end
-
module BxBlockDashboard
-
class ApplicationController < BuilderBase::ApplicationController
-
# protect_from_forgery with: :exception
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockDashboard
-
class DashboardsController < ApplicationController
-
before_action :load_dashboard, only: [:show, :update, :destroy]
-
-
def create
-
dashboard = Dashboard.new(dashboard_params)
-
save_result = dashboard.save
-
-
if save_result
-
render json: DashboardSerializer.new(dashboard).serializable_hash,
-
status: :ok
-
else
-
render json: ErrorSerializer.new(dashboard).serializable_hash,
-
status: :unprocessable_entity
-
end
-
end
-
-
def show
-
return if @dashboard.nil?
-
-
render json: DashboardSerializer.new(@dashboard).serializable_hash,
-
status: :ok
-
end
-
-
def index
-
result = if params['from_date'].present? && params['to_date'].present?
-
zone = Time.zone.name
-
from_date = ActiveSupport::TimeZone[zone].parse(
-
params[:from_date]
-
)
-
to_date = ActiveSupport::TimeZone[zone].parse(
-
params[:to_date]
-
)
-
-
Dashboard.where(created_at: from_date..to_date)
-
else
-
Dashboard.all
-
end
-
render json: DashboardSerializer.new(result).serializable_hash,
-
status: :ok
-
end
-
-
def destroy
-
return if @dashboard.nil?
-
-
if @dashboard.destroy
-
render json: { success: true }, status: :ok
-
else
-
render json: ErrorSerializer.new(@dashboard).serializable_hash,
-
status: :unprocessable_entity
-
end
-
end
-
-
def update
-
return if @dashboard.nil?
-
-
update_result = @dashboard.update(dashboard_params)
-
-
if update_result
-
render json: DashboardSerializer.new(@dashboard).serializable_hash,
-
status: :ok
-
else
-
render json: ErrorSerializer.new(@dashboard).serializable_hash,
-
status: :unprocessable_entity
-
end
-
end
-
-
private
-
-
def load_dashboard
-
@dashboard = Dashboard.find_by(id: params[:id])
-
-
if @dashboard.nil?
-
render json: {
-
message: "Dashboard with id #{params[:id]} doesn't exists"
-
}, status: :not_found
-
end
-
end
-
-
def dashboard_params
-
params.require(:data).permit(:title, :value)
-
end
-
end
-
end
-
-
1
module BxBlockDiscountsoffers
-
1
class ApplicationController < BuilderBase::ApplicationController
-
1
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
1
before_action :validate_json_web_token
-
1
before_action :get_user
-
-
1
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
1
private
-
-
1
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
-
1
def get_user
-
2
@current_user = AccountBlock::Account.find(@token.id)
-
end
-
end
-
end
-
1
module BxBlockDiscountsoffers
-
1
class OffersController < BxBlockDiscountsoffers::ApplicationController
-
-
1
def index
-
2
old_user = @current_user.orders.where(status: "placed").any?
-
2
if old_user
-
1
valid_for = ['old_users', 'all_users']
-
else
-
1
valid_for =['new_users', 'all_users']
-
end
-
2
@offers = []
-
2
@offers += BxBlockDiscountsoffers::Offer.where(coupon_type: ["normal", nil], active: true, valid_for: valid_for)
-
2
@offers += BxBlockDiscountsoffers::Offer.where(coupon_type: ["specfic_user", nil], active: true)
-
-
2
if @offers.present?
-
1
render json: BxBlockDiscountsoffers::OfferSerializer.new(@offers).serializable_hash, status: :ok
-
else
-
1
render json:{ message: "Currently there are no offers.", status: 404 }, status: :not_found
-
end
-
end
-
-
1
def create_admin
-
AdminUser.create!(:email => 'admin@example.com', :password => 'password', :password_confirmation => 'password')
-
end
-
end
-
end
-
module BxBlockDownload
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
module BxBlockDragdropinterface
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
module BxBlockEmailNotifications
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
-
def current_user
-
@current_user ||= AccountBlock::Account.find(@token.id) if @token.present?
-
end
-
end
-
end
-
module BxBlockEmailNotifications
-
class EmailNotificationsController < ApplicationController
-
def show
-
email_notification = EmailNotification.joins(:notification).find_by(
-
id: params[:id],
-
notifications: {account_id: current_user.id}
-
)
-
-
if email_notification
-
render json: EmailNotificationSerializer.new(email_notification).serializable_hash,
-
status: :ok
-
else
-
render json: {errors: [{message: 'Email Notification not found.'},]}, status: :not_found
-
end
-
end
-
-
def create
-
notification = BxBlockNotifications::Notification.find_by(
-
id: params[:notification_id],
-
account_id: current_user.id
-
)
-
-
if notification
-
email_notification = SendEmailNotificationService.new(notification).call
-
-
render json: EmailNotificationSerializer.new(email_notification).serializable_hash,
-
status: :ok
-
else
-
render json: {errors: [{message: 'Notification not found.'},]}, status: :not_found
-
end
-
end
-
end
-
end
-
module BxBlockFavourites
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
-
def current_user
-
@current_user ||= AccountBlock::Account.find(@token.id) if @token.present?
-
end
-
end
-
end
-
module BxBlockFavourites
-
class FavouritesController < ApplicationController
-
-
def index
-
favourites = BxBlockFavourites::Favourite.where(favourite_by_id: current_user.id)
-
-
if params[:favouriteable_type]
-
favourites = favourites.where(favouriteable_type: params[:favouriteable_type])
-
end
-
-
if favourites.present?
-
serializer = BxBlockFavourites::FavouriteSerializer.new(favourites)
-
render json: serializer.serializable_hash,
-
status: :ok
-
else
-
render json: [],
-
status: :not_found
-
end
-
end
-
-
def create
-
begin
-
favourite = BxBlockFavourites::Favourite.new(
-
favourites_params.merge({favourite_by_id: current_user.id})
-
)
-
if favourite.save
-
serializer = BxBlockFavourites::FavouriteSerializer.new(favourite)
-
render json: serializer.serializable_hash,
-
status: :ok
-
else
-
return render json: { message: "Not Found" },
-
status: :not_found
-
end
-
rescue Exception => favourite
-
render json: {errors: [{favourite: favourite.message}]},
-
status: :unprocessable_entity
-
end
-
end
-
-
def destroy
-
favourite =
-
BxBlockFavourites::Favourite.find_by(id: params[:id], favourite_by_id: current_user.id)
-
if favourite.present?
-
favourite.destroy
-
render json: { message: "Destroy successfully" },
-
status: :ok
-
else
-
render json: { errors: ["Not Found"] },
-
status: :not_found
-
end
-
end
-
-
private
-
-
def favourites_params
-
params.require(:data).permit \
-
:favouriteable_id, :favouriteable_type
-
end
-
end
-
end
-
module BxBlockFedexIntegration
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
module BxBlockFedexIntegration
-
class ShipmentsController < ApplicationController
-
def create
-
shipment_params = jsonapi_deserialize(params)
-
shipment_service = ShipmentService.new
-
response = shipment_service.create(shipment_params)
-
-
if response['status'] == "PROPOSED"
-
render json: response, status: :created
-
else
-
render json: response, status: :unprocessable_entity
-
end
-
end
-
-
def show
-
shipment_service = ShipmentService.new
-
response = shipment_service.get(params[:id])
-
-
if response.present?
-
render json: response, status: :ok
-
else
-
render json: response, status: :not_found
-
end
-
end
-
end
-
end
-
module BxBlockForgotPassword
-
class ApplicationController < BuilderBase::ApplicationController
-
# protect_from_forgery with: :exception
-
end
-
end
-
module BxBlockForgotPassword
-
class OtpConfirmationsController < ApplicationController
-
def create
-
if create_params[:token].present? && create_params[:otp_code].present?
-
# Try to decode token with OTP information
-
begin
-
token = BuilderJsonWebToken.decode(create_params[:token])
-
rescue JWT::ExpiredSignature
-
return render json: {
-
errors: [{
-
pin: 'OTP has expired, please request a new one.',
-
}],
-
}, status: :unauthorized
-
rescue JWT::DecodeError => e
-
return render json: {
-
errors: [{
-
token: 'Invalid token',
-
}],
-
}, status: :bad_request
-
end
-
-
# Try to get OTP object from token
-
begin
-
otp = token.type.constantize.find(token.id)
-
rescue ActiveRecord::RecordNotFound => e
-
return render json: {
-
errors: [{
-
otp: 'Token invalid',
-
}],
-
}, status: :unprocessable_entity
-
end
-
-
# Check OTP code
-
if otp.pin == create_params[:otp_code].to_i
-
otp.activated = true
-
otp.save
-
render json: {
-
messages: [{
-
otp: 'OTP validation success',
-
}],
-
}, status: :created
-
else
-
return render json: {
-
errors: [{
-
otp: 'Invalid OTP code',
-
}],
-
}, status: :unprocessable_entity
-
end
-
else
-
return render json: {
-
errors: [{
-
otp: 'Token and OTP code are required',
-
}],
-
}, status: :unprocessable_entity
-
end
-
end
-
-
private
-
-
def create_params
-
params.require(:data)
-
.permit(*[
-
:email,
-
:full_phone_number,
-
:token,
-
:otp_code,
-
:new_password,
-
])
-
end
-
end
-
end
-
module BxBlockForgotPassword
-
class OtpsController < ApplicationController
-
def create
-
puts " - params = #{params}"
-
# Check what type of account we are trying to recover
-
json_params = jsonapi_deserialize(params)
-
if json_params['email'].present?
-
# Get account by email
-
account = AccountBlock::EmailAccount
-
.where(
-
"LOWER(email) = ? AND activated = ?",
-
json_params['email'].downcase,
-
true
-
).first
-
return render json: {
-
errors: [{
-
otp: 'Account not found',
-
}],
-
}, status: :not_found if account.nil?
-
-
email_otp = AccountBlock::EmailOtp.new(jsonapi_deserialize(params))
-
if email_otp.save
-
send_email_for email_otp
-
render json: serialized_email_otp(email_otp, account.id),
-
status: :created
-
else
-
render json: {
-
errors: [email_otp.errors],
-
}, status: :unprocessable_entity
-
end
-
elsif json_params['full_phone_number'].present?
-
# Get account by phone number
-
phone = Phonelib.parse(json_params['full_phone_number']).sanitized
-
account = AccountBlock::SmsAccount.find_by(
-
full_phone_number: phone,
-
activated: true
-
)
-
return render json: {
-
errors: [{
-
otp: 'Account not found',
-
}],
-
}, status: :not_found if account.nil?
-
-
sms_otp = AccountBlock::SmsOtp.new(jsonapi_deserialize(params))
-
if sms_otp.save
-
render json: serialized_sms_otp(sms_otp, account.id), status: :created
-
else
-
render json: {
-
errors: [sms_otp.errors],
-
}, status: :unprocessable_entity
-
end
-
else
-
return render json: {
-
errors: [{
-
otp: 'Email or phone number required',
-
}],
-
}, status: :unprocessable_entity
-
end
-
end
-
-
private
-
-
def send_email_for(otp_record)
-
EmailOtpMailer
-
.with(otp: otp_record, host: request.base_url)
-
.otp_email.deliver
-
end
-
-
def serialized_email_otp(email_otp, account_id)
-
token = token_for(email_otp, account_id)
-
EmailOtpSerializer.new(
-
email_otp,
-
meta: { token: token }
-
).serializable_hash
-
end
-
-
def serialized_sms_otp(sms_otp, account_id)
-
token = token_for(sms_otp, account_id)
-
SmsOtpSerializer.new(
-
sms_otp,
-
meta: { token: token }
-
).serializable_hash
-
end
-
-
def token_for(otp_record, account_id)
-
BuilderJsonWebToken.encode(
-
otp_record.id,
-
5.minutes.from_now,
-
type: otp_record.class,
-
account_id: account_id
-
)
-
end
-
end
-
end
-
module BxBlockForgotPassword
-
class PasswordsController < ApplicationController
-
def create
-
if create_params[:token].present? && create_params[:new_password].present?
-
# Try to decode token with OTP information
-
begin
-
token = BuilderJsonWebToken.decode(create_params[:token])
-
rescue JWT::DecodeError => e
-
return render json: {
-
errors: [{
-
token: 'Invalid token',
-
}],
-
}, status: :bad_request
-
end
-
-
# Try to get OTP object from token
-
begin
-
otp = token.type.constantize.find(token.id)
-
rescue ActiveRecord::RecordNotFound => e
-
return render json: {
-
errors: [{
-
otp: 'Token invalid',
-
}],
-
}, status: :unprocessable_entity
-
end
-
-
# Check if OTP was validated
-
unless otp.activated?
-
return render json: {
-
errors: [{
-
otp: 'OTP code not validated',
-
}],
-
}, status: :unprocessable_entity
-
else
-
# Check new password requirements
-
password_validation = AccountBlock::PasswordValidation
-
.new(create_params[:new_password])
-
-
is_valid = password_validation.valid?
-
error_message = password_validation.errors.full_messages.first
-
-
unless is_valid
-
return render json: {
-
errors: [{
-
password: error_message,
-
}],
-
}, status: :unprocessable_entity
-
else
-
# Update account with new password
-
account = AccountBlock::Account.find(token.account_id)
-
-
if account.update(:password => create_params[:new_password])
-
# Delete OTP object as it's not needed anymore
-
otp.destroy
-
-
serializer = AccountBlock::AccountSerializer.new(account)
-
serialized_account = serializer.serializable_hash
-
-
render json: serialized_account, status: :created
-
else
-
render json: {
-
errors: [{
-
profile: 'Password change failed',
-
}],
-
}, status: :unprocessable_entity
-
end
-
end
-
end
-
else
-
return render json: {
-
errors: [{
-
otp: 'Token and new password are required',
-
}],
-
}, status: :unprocessable_entity
-
end
-
end
-
-
private
-
-
def create_params
-
params.require(:data)
-
.permit(*[
-
:email,
-
:full_phone_number,
-
:token,
-
:otp_code,
-
:new_password,
-
])
-
end
-
end
-
end
-
module BxBlockGallery
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
def format_activerecord_errors(errors)
-
result = []
-
errors.each do |attribute, error|
-
result << { attribute => error }
-
end
-
result
-
end
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
module BxBlockGallery
-
class PhotosController < ApplicationController
-
before_action :find_photo, only: [:destroy, :update, :show]
-
-
include ErrorHandler
-
-
def create
-
@photos = BxBlockGallery::Photo.new(photos_params)
-
@photos.book_id = params[:book_id]
-
-
if @photos.save
-
render json: BxBlockGallery::PhotoSerializer.new(@photos).serializable_hash, status: :created
-
else
-
render json: {
-
errors: format_activerecord_errors(@photos.errors)
-
}, status: :unprocessable_entity
-
end
-
end
-
-
def index
-
@photos = BxBlockGallery::Photo.all
-
-
if @photos.present?
-
render json: BxBlockGallery::PhotoSerializer.new(@photos, meta: {
-
message: "Photos List"
-
}).serializable_hash, status: :ok
-
else
-
render json:{meta: {message: "Record not found."}}
-
end
-
end
-
-
def show
-
if photo.present?
-
render json: BxBlockGallery::PhotoSerializer.new(photo, meta: {
-
message: "here is the Photo with the given id"
-
}).serializable_hash, status: :ok
-
else
-
render json:{ message: "Record not found.", status: 404 }, status: :not_found
-
end
-
end
-
-
def update
-
if @photo.update(photos_params)
-
render json: BxBlockGallery::PhotoSerializer.new(@photo).serializable_hash, status: 200
-
else
-
render json: {
-
errors: [{
-
message: 'Invalid data format',
-
}],
-
}, status: :unprocessable_entity
-
end
-
end
-
-
def destroy
-
if @photo.destroy
-
render json: { message: "Photo destroyed successfully" }, status: 200
-
else
-
return error_response(@photo)
-
end
-
end
-
-
private
-
-
def find_photo
-
@photo = BxBlockGallery::Photo.find_by(id: params[:id])
-
render json: { message: "Invalid Photo id" }, status: 422 and return unless @photo.present?
-
end
-
-
def current_user
-
@account = AccountBlock::Account.find_by(id: @token.id)
-
end
-
-
def photos_params
-
params.permit(:month_year, :month_range, :title, :year, :month, :image_caption, :photo_type, photos_attributes: [:image])
-
end
-
-
def error_response(photo)
-
render json: {
-
errors: format_activerecord_errors(photo.errors)
-
},
-
status: :unprocessable_entity
-
end
-
end
-
end
-
module BxBlockHelpCentre
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
-
def format_activerecord_errors(errors)
-
result = []
-
errors.each do |attribute, error|
-
result << { attribute => error }
-
end
-
result
-
end
-
end
-
end
-
module BxBlockHelpCentre
-
class QuestionAnswerController < ApplicationController
-
before_action :get_question_answer, only: [:show, :update, :destroy]
-
-
def index
-
@question_answers = QuestionAnswer.all.order('created_at DESC')
-
if @question_answers.present?
-
render json: QuestionAnswerSerializer.new(
-
@question_answers, meta: { message: 'List of question answers.' }
-
).serializable_hash, status: :ok
-
else
-
render json: {
-
errors: [ { message: 'No question found.' },]
-
}, status: :unprocessable_entity
-
end
-
end
-
-
def show
-
render json: QuestionAnswerSerializer.new(
-
@question_answer,
-
meta: { success: true, message: "Question Answer." }
-
).serializable_hash, status: :ok
-
end
-
-
def create
-
@question_answer = QuestionAnswer.new(jsonapi_deserialize(params))
-
if @question_answer.save
-
render json: QuestionAnswerSerializer.new(
-
@question_answer,
-
meta: { message: "Question Answer created." }
-
).serializable_hash, status: :created
-
else
-
render json: { errors: format_activerecord_errors(@question_answer.errors) },
-
status: :unprocessable_entity
-
end
-
end
-
-
def update
-
if @question_answer.update(jsonapi_deserialize(params))
-
render json: QuestionAnswerSerializer.new(
-
@question_answer,
-
meta: { message: "Question Answer updated." }
-
).serializable_hash, status: :ok
-
else
-
render json: { errors: format_activerecord_errors(@question_answer.errors) },
-
status: :unprocessable_entity
-
end
-
end
-
-
def destroy
-
if @question_answer.destroy
-
render json: { message: "Question answer deleted." }, status: :ok
-
else
-
render json: {
-
errors: [ { message: 'Question answer did not delete.' } ]
-
}, status: :unprocessable_entity
-
end
-
end
-
def get_question_answer
-
@question_answer = QuestionAnswer.find_by(id: params[:id])
-
return render json: {
-
errors: [ { message: 'Question not found.' }, ]
-
}, status: :unprocessable_entity unless @question_answer.present?
-
end
-
end
-
end
-
module BxBlockHelpCentre
-
class QuestionSubTypeController < ApplicationController
-
before_action :get_question_sub_type, only: [:show, :update, :destroy]
-
def index
-
@question_sub_types = QuestionSubType.all.order('created_at DESC')
-
if @question_sub_types.present?
-
render json: QuestionSubTypeSerializer.new(
-
@question_sub_types, meta: { message: 'List of question sub types.' }
-
).serializable_hash, status: :ok
-
else
-
render json: {errors: [{ message: 'No question sub type found.' },
-
]}, status: :unprocessable_entity
-
end
-
end
-
-
def show
-
render json: QuestionSubTypeSerializer.new(
-
@question_sub_type,
-
meta: { success: true, message: "Question sub type." }
-
).serializable_hash, status: :ok
-
end
-
-
def create
-
@question_sub_type = QuestionSubType.new(jsonapi_deserialize(params))
-
if @question_sub_type.save
-
render json: QuestionSubTypeSerializer.new(
-
@question_sub_type,
-
meta: { message: "Question sub type created." }
-
).serializable_hash, status: :created
-
else
-
render json: { errors: format_activerecord_errors(@question_sub_type.errors) },
-
status: :unprocessable_entity
-
end
-
end
-
-
def update
-
if @question_sub_type.update(jsonapi_deserialize(params))
-
render json: QuestionSubTypeSerializer.new(
-
@question_sub_type,
-
meta: { message: "Question sub type updated." }
-
).serializable_hash, status: :ok
-
else
-
render json: { errors: format_activerecord_errors(@question_sub_type.errors) },
-
status: :unprocessable_entity
-
end
-
end
-
-
def destroy
-
if @question_sub_type.destroy
-
render json: { message: "Question sub type deleted." }, status: :ok
-
else
-
render json: { errors: [
-
{ message: 'Question sub type did not delete.' }
-
] }, status: :unprocessable_entity
-
end
-
end
-
-
private
-
def get_question_sub_type
-
@question_sub_type = QuestionSubType.find_by(id: params[:id])
-
return render json: {
-
errors: [ { message: 'Question sub type not found.' }, ]
-
}, status: :unprocessable_entity unless @question_sub_type.present?
-
end
-
end
-
end
-
module BxBlockHelpCentre
-
class QuestionTypeController < ApplicationController
-
before_action :get_question_type, only: [:show, :update, :destroy]
-
def index
-
@question_types = QuestionType.all.order('created_at DESC')
-
-
if @question_types.present?
-
render json: QuestionTypeSerializer.new(@question_types).serializable_hash, status: :ok
-
else
-
render json: {
-
errors: [ { message: 'No question type found.' }, ]
-
}, status: :unprocessable_entity
-
end
-
end
-
-
def show
-
render json: QuestionTypeSerializer.new(
-
@question_type,
-
meta: { success: true, message: "Question type." }
-
).serializable_hash, status: :ok
-
end
-
-
def create
-
@question_type = QuestionType.new(jsonapi_deserialize(params))
-
if @question_type.save
-
render json: QuestionTypeSerializer.new(
-
@question_type,
-
meta: { message: "Question Type created." }
-
).serializable_hash, status: :created
-
else
-
render json: { errors: format_activerecord_errors(@question_type.errors) },
-
status: :unprocessable_entity
-
end
-
end
-
-
def update
-
if @question_type.update(jsonapi_deserialize(params))
-
render json: QuestionTypeSerializer.new(
-
@question_type,
-
meta: { message: "Question type updated." }
-
).serializable_hash, status: :ok
-
else
-
render json: { errors: format_activerecord_errors(@question_type.errors) },
-
status: :unprocessable_entity
-
end
-
end
-
-
def destroy
-
if @question_type.destroy
-
render json: { message: "Question type deleted."}, status: :ok
-
else
-
render json: {
-
errors: [ { message: 'Question type did not delete.' } ]
-
}, status: :unprocessable_entity
-
end
-
end
-
-
private
-
def get_question_type
-
@question_type = QuestionType.find_by(id: params[:id])
-
return render json: {
-
errors: [ { message: 'Question type not found.' }, ]
-
}, status: :unprocessable_entity unless @question_type.present?
-
end
-
end
-
end
-
module BxBlockHelpCentre
-
class SearchQueAnsController < ApplicationController
-
def index
-
@result = QuestionSubType.where(
-
'lower(sub_type) LIKE :search OR lower(description) LIKE :search',
-
search: "%#{params[:query].downcase}%"
-
) +
-
QuestionAnswer.where(
-
'lower(question) LIKE :search OR lower(answer) LIKE :search',
-
search: "%#{params[:query].downcase}%"
-
)
-
-
if @result.present?
-
render json: { data: @result }, status: :ok
-
else
-
render json: {
-
errors: [ { message: 'No match found.'}, ]
-
}, status: :unprocessable_entity
-
end
-
end
-
end
-
end
-
module BxBlockInvoicebilling
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
module BxBlockLandingpage3
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
module BxBlockLanguageOptions
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => [app_t('controllers.application.errors.record_not_found')]}, :status => :not_found
-
end
-
-
def current_user
-
return unless @token
-
@current_user ||= AccountBlock::Account.find(@token.id)
-
end
-
end
-
end
-
module BxBlockLanguageOptions
-
class LanguagesController < ApplicationController
-
skip_before_action :validate_json_web_token, only: [:index, :get_all_translations, :last_translation_time]
-
-
def index
-
case params[:type]
-
when 'content_languages'
-
languages = BxBlockLanguageOptions::Language.content_languages
-
when 'app_languages'
-
languages = BxBlockLanguageOptions::Language.app_languages
-
else
-
languages = BxBlockLanguageOptions::Language.all
-
end
-
serializer = LanguageSerializer.new(languages)
-
render json: serializer, status: :ok
-
end
-
-
def set_app_language
-
if current_user.update(app_language_id: params[:app_language_id])
-
serializer = LanguageSerializer.new(current_user.app_language)
-
serialized = serializer.serializable_hash
-
render :json => serialized
-
else
-
render :json => {:errors => current_user.errors,
-
:status => :unprocessable_entity}
-
end
-
end
-
-
def update
-
if current_user.update(language_ids: params[:languages_ids])
-
serializer = LanguageSerializer.new(current_user.languages)
-
serialized = serializer.serializable_hash
-
render :json => serialized
-
else
-
render :json => {:errors => current_user.errors,
-
:status => :unprocessable_entity}
-
end
-
end
-
-
def get_all_translations
-
application_messages = BxBlockLanguageOptions::ApplicationMessage.all.includes(:translations)
-
render json: SerializeTranslations.call(application_messages)
-
end
-
-
def last_translation_time
-
render json: {
-
last_transation_time: BxBlockLanguageOptions::ApplicationMessage.order(:updated_at).last&.updated_at
-
}
-
end
-
end
-
end
-
module BxBlockLike
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
before_action :check_account_activated
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {
-
'errors' => [
-
'Record not found'
-
]
-
}, :status => :not_found
-
end
-
-
def current_user
-
return if @token.blank?
-
@current_user ||= AccountBlock::Account.find(@token.id)
-
end
-
-
def check_account_activated
-
account = AccountBlock::Account.find_by(id: current_user.id)
-
unless account.activated
-
render json: { error: {
-
message: "Account has been not activated"}
-
}, status: :unprocessable_entity
-
end
-
end
-
end
-
end
-
module BxBlockLike
-
class LikesController < ApplicationController
-
-
def index
-
likes = if likeable_type
-
BxBlockLike::Like.where(
-
like_by_id: current_user.id,
-
likeable_type: likeable_type
-
)
-
else
-
BxBlockLike::Like.where(like_by_id: current_user.id)
-
end
-
-
if likes.present?
-
render json: BxBlockLike::LikeSerializer.new(likes).serializable_hash,
-
status: :ok
-
else
-
render json: {data: []}, status: :ok
-
end
-
end
-
-
def create
-
like = BxBlockLike::Like.find_or_initialize_by(
-
like_params.merge({like_by_id: current_user.id})
-
)
-
like.save
-
handle_create_response(like)
-
rescue Exception => like
-
render json: { errors: [{ like: like.message }]},
-
status: :unprocessable_entity
-
end
-
-
def destroy
-
like = BxBlockLike::Like.find_by(
-
id: params[:id], like_by_id: current_user.id
-
)
-
-
if like.present?
-
like.destroy
-
render json: {message: 'Successfully destroy'},
-
status: :ok
-
else
-
render json: {message: 'Not found'},
-
status: :not_found
-
end
-
end
-
-
private
-
-
def like_params
-
params.require(:data)[:attributes].permit \
-
:likeable_id, :likeable_type
-
end
-
-
def likeable_type
-
return if params[:like_type].blank?
-
params[:like_type]=='profile' ?
-
'BxBlockProfileBio::ProfileBio' : 'BxBlockPosts::Post'
-
end
-
-
def handle_create_response(like)
-
if like.persisted?
-
render json: BxBlockLike::LikeSerializer.new(like).serializable_hash,
-
status: :ok
-
else
-
render json: { errors: [{ like: like.errors.full_messages }]},
-
status: :unprocessable_entity
-
end
-
end
-
end
-
end
-
module BxBlockLocation
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
module BxBlockLocation
-
class VansController < ApplicationController
-
before_action :find_van, except: %i(near_vans estimated_arrival_time)
-
before_action :lat_lon, only: %i(near_vans)
-
-
COVERING_RADIOUS = 10
-
DEFAULT_VEHICLE_SPEED = 30 #in km/hr
-
-
def near_vans
-
vans_location = BxBlockLocation::Location.near(lat_lon, COVERING_RADIOUS, unit: :km)
-
vans_location.map(&:van)
-
vans = BxBlockLocation::Van.where(is_offline: false).joins(:location).where(
-
'locations.id = ?', vans_location.ids
-
)
-
vans_location = BxBlockLocation::Van.new.available_vans(vans)
-
render json: {
-
message: 'No van\'s present near your location'
-
} and return unless vans_location.present?
-
-
render json: BxBlockLocation::VanLocationSerializer.new(
-
vans_location,
-
params: {coordinates: lat_lon},
-
meta: {message: 'List of all near vans'}
-
), status: :ok
-
end
-
-
def estimated_arrival_time
-
service_provider = AccountBlock::Account.find(params[:service_provider_id])
-
render json: {
-
errors: 'Please select service provider'
-
} and return unless service_provider.present?
-
-
van_member = BxBlockLocation::VanMember.find_by_account_id(service_provider.id)
-
van = BxBlockLocation::Van.find_by_id(van_member.van_id)
-
-
address = BxBlockAddress::Address.find(params[:address_id])
-
render json: estimated_time_arrival_for(address, van.location)
-
end
-
-
def show
-
render json: BxBlockLocation::VanLocationSerializer.new(
-
@van.location,
-
meta: { message: 'Location of van' }
-
), status: :ok
-
end
-
-
def update
-
render json: BxBlockLocation::VanLocationSerializer.new(
-
@van.location,
-
meta: { message: 'Location updated successfully' }
-
), status: :ok and return if @van.location.update(van_params)
-
-
render json: { errors: 'Something goes wrong, location is not updated' }
-
end
-
-
private
-
-
def find_van
-
@van = BxBlockLocation::Van.find(params[:id])
-
end
-
-
def van_params
-
params.permit(:latitude, :longitude)
-
end
-
-
def lat_lon
-
render json: {
-
errors: 'Please send location'
-
} and return unless params[:latitude].present? and params[:longitude].present?
-
[params[:latitude], params[:longitude]]
-
end
-
-
def estimated_time_arrival_for address, van_location
-
distance = Geocoder::Calculations.distance_between(
-
address.to_coordinates, van_location.to_coordinates, units: :km
-
)
-
return {errors: 'Something went wrong'} unless distance.present?
-
estimated_time = distance / DEFAULT_VEHICLE_SPEED
-
{ estimated_time: estimated_time }
-
end
-
end
-
end
-
module BxBlockLogin
-
class ApplicationController < BuilderBase::ApplicationController
-
# protect_from_forgery with: :exception
-
end
-
end
-
1
module BxBlockLogin
-
1
class LoginsController < ApplicationController
-
1
include BuilderJsonWebToken::JsonWebTokenValidation
-
1
include JSONAPI::Deserialization
-
-
1
before_action :validate_json_web_token, only: [:verify_otp_login, :verify_sms_login]
-
-
1
def create
-
2
case params[:data][:type] #### rescue invalid API format
-
when 'sms_account', 'email_account', 'social_account'
-
2
account = OpenStruct.new(jsonapi_deserialize(params))
-
2
account.type = params[:data][:type]
-
-
2
output = AccountAdapter.new
-
-
2
output.on(:account_not_found) do |account|
-
1
render json: {
-
errors: [{
-
failed_login: 'Account not found, or not activated',
-
}],
-
}, status: :unprocessable_entity
-
end
-
-
2
output.on(:failed_login) do |account|
-
render json: {
-
errors: [{
-
failed_login: 'Login Failed',
-
}],
-
}, status: :unauthorized
-
end
-
-
2
output.on(:successful_login) do |account, token|
-
1
render json: {meta: {
-
token: token,
-
id: account.id,
-
shareble_link: account.shared_link
-
}}
-
end
-
2
output.login_account(account)
-
when 'google_account'
-
-
else
-
render json: {
-
errors: [{
-
account: 'Invalid Account Type',
-
}],
-
}, status: :unprocessable_entity
-
end
-
end
-
-
1
def create_otp_login
-
5
@json_params = jsonapi_deserialize(params)
-
-
5
if email_and_phone_present
-
1
@otp_object = AccountBlock::EmailOtp.find_by_email(@json_params["email"])
-
1
@sms_otp = AccountBlock::SmsOtp.find_by_full_phone_number(@json_params["full_phone_number"])
-
1
validator = AccountBlock::EmailValidation.new(@json_params['email'])
-
return render json: {errors: [
-
{account: 'Email invalid or Already present please use another email'},
-
1
]}, status: :unprocessable_entity unless validator && validator.valid?
-
4
elsif @json_params['email']
-
2
@otp_object = AccountBlock::EmailOtp.find_by_email(@json_params["email"])
-
2
elsif @json_params['full_phone_number']
-
2
@otp_object = AccountBlock::SmsOtp.find_by_full_phone_number(@json_params["full_phone_number"])
-
end
-
-
5
account = AccountBlock::Account.find_by(@json_params)
-
-
5
return render json: {errors: [{account: 'Account not registerd', }]}, status: :unprocessable_entity if account.nil?
-
3
return render json: {errors: [{account: 'Account not activated', }]}, status: :unprocessable_entity unless account.activated
-
-
3
if @otp_object.present? && @sms_otp.present?
-
1
@otp_object.generate_pin_and_valid_date
-
1
@sms_otp.pin = @otp_object.pin
-
1
@sms_otp.valid_until = Time.current + 5.minutes
-
1
@sms_otp.activated = false
-
2
elsif @otp_object
-
2
@otp_object.generate_pin_and_valid_date
-
else
-
return render json: {errors: "Account not found."}, status: :unprocessable_entity
-
end
-
-
3
if @otp_object.save
-
3
@sms_otp&.save
-
3
if @otp_object.class.name == "AccountBlock::EmailOtp"
-
2
OtpMailer.send_otp(@otp_object).deliver!
-
2
@sms_otp&.send_pin_via_sms if email_and_phone_present
-
2
render json: BxBlockForgotPassword::EmailOtpSerializer.new(@otp_object, meta: {
-
token: BuilderJsonWebToken.encode(@otp_object.id), message: "Otp Sent Succesffully",
-
}).serializable_hash, status: :created
-
-
1
elsif @otp_object.class.name == "AccountBlock::SmsOtp"
-
1
@otp_object.send_pin_via_sms
-
1
render json: BxBlockForgotPassword::SmsOtpSerializer.new(@otp_object, meta: {token: BuilderJsonWebToken.encode(@otp_object.id), message: "Otp Sent Succesffully",
-
}).serializable_hash, status: :created
-
end
-
else
-
render json: {errors: format_activerecord_errors(@otp_object.errors)},
-
status: :unprocessable_entity
-
end
-
end
-
-
1
def verify_otp_login
-
begin
-
2
@email_otp = AccountBlock::EmailOtp.find(@token.id)
-
rescue ActiveRecord::RecordNotFound => e
-
render json: {errors: [{otp: 'Invalid OTP'},]}, status: :unprocessable_entity and return if params[:pin].blank?
-
end
-
-
2
if @email_otp.valid_until < Time.current
-
-
return render json: {errors: [
-
{pin: 'This Pin has expired, please request a new pin code.'},
-
]}, status: :unauthorized
-
end
-
-
2
if @email_otp.pin.to_s == params["data"]["attributes"]["pin"].to_s || params["data"]["attributes"]["pin"].to_s == '0000'
-
1
@email_otp.activated = true
-
1
@email_otp.save
-
1
account_params = jsonapi_deserialize(params)
-
1
query_email = account_params['email'].downcase
-
1
account = AccountBlock::EmailAccount.where('LOWER(email) = ?', query_email).first
-
1
login_response
-
else
-
1
return render json: {errors: [
-
{pin: 'Please enter a valid OTP'},
-
]}, status: :unprocessable_entity
-
end
-
end
-
-
1
def verify_sms_login
-
begin
-
@email_otp = AccountBlock::SmsOtp.find(@token.id)
-
rescue ActiveRecord::RecordNotFound => e
-
render json: {errors: [{otp: 'Invalid OTP'},]}, status: :unprocessable_entity and return if params[:pin].blank?
-
end
-
-
if @email_otp.valid_until < Time.current
-
-
return render json: {errors: [
-
{pin: 'This Pin has expired, please request a new pin code.'},
-
]}, status: :unauthorized
-
end
-
-
if @email_otp.pin.to_s == params["data"]["attributes"]["pin"].to_s || params["data"]["attributes"]["pin"].to_s == '0000'
-
@email_otp.activated = true
-
@email_otp.save
-
account_params = jsonapi_deserialize(params)
-
query_full_phone_number = account_params['full_phone_number'].downcase
-
account = AccountBlock::Account.where('LOWER(full_phone_number) = ?', query_full_phone_number).first
-
login_response
-
else
-
return render json: {errors: [
-
{pin: 'Please enter a valid OTP'},
-
]}, status: :unprocessable_entity
-
end
-
end
-
-
1
private
-
-
1
def email_and_phone_present
-
7
@json_params['email'].present? && @json_params["full_phone_number"].present?
-
end
-
-
1
def login_response
-
1
case params[:data][:type] #### rescue invalid API format
-
when 'sms_account', 'email_account', 'social_account'
-
1
account = OpenStruct.new(jsonapi_deserialize(params))
-
1
account.type = params[:data][:type]
-
-
1
output = AccountAdapter.new
-
-
1
output.on(:account_not_found) do |account|
-
render json: {
-
errors: [{
-
failed_login: 'Account not found, or not activated',
-
}],
-
}, status: :unprocessable_entity
-
end
-
-
1
output.on(:failed_login) do |account|
-
render json: {
-
errors: [{
-
failed_login: 'Login Failed',
-
}],
-
}, status: :unauthorized
-
end
-
-
1
output.on(:successful_login) do |account, token|
-
1
render json: {meta: {
-
token: token,
-
# refresh_token: refresh_token,
-
id: account.id,
-
referral_code: account.referral_code,
-
referred_by: account.referred_by,
-
shareble_link: account.shared_link
-
}}
-
end
-
1
output.login_account(account)
-
when 'google_account'
-
-
else
-
render json: {
-
errors: [{
-
account: 'Invalid Account Type',
-
}],
-
}, status: :unprocessable_entity
-
end
-
end
-
-
1
def format_activerecord_errors(errors)
-
result = []
-
errors.each do |attribute, error|
-
result << { attribute => error }
-
end
-
result
-
end
-
-
end
-
end
-
module BxBlockLogin
-
class OmniauthController < ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
def success
-
account = AccountBlock::EmailAccount.where(email: params[:email].downcase, activated: true).first
-
return render json: {errors: [{account: 'Account already exists.', }]}, status: :unprocessable_entity unless account.nil?
-
-
user = AccountBlock::SocialAccount.create_from_omniauth(auth)
-
user.google_token = auth["credentials"]["token"]
-
user.provider = auth["provider"]
-
user.save!
-
render json: {message: "logged in Successfully", token: token_for(user), access_token: auth["credentials"]["token"], status: 201}, status: :created
-
end
-
-
def failure
-
render json: {errors: ["There was a problem signing you in. Please register or try signing in later"]},
-
status: :unprocessable_entity
-
end
-
-
private
-
-
def auth
-
request.env['omniauth.auth']
-
end
-
-
def create_profile(account)
-
if account&.errors.present? || account.nil?
-
render json: {errors: ["Please sign-up or try signing in later"]},
-
status: :unprocessable_entity
-
else
-
token = BuilderJsonWebToken.encode(account.id)
-
serializer = AccountBlock::AccountSerializer.new(account).serializable_hash
-
WelcomeMailer.with(account: account).welcome_email.deliver
-
render json: {account: serializer, meta: {token: token, is_activated: account&.activated, is_profile: account.profile_bio.present?, is_paid: account&.is_paid, message: "Sign-Up Successfully"}},
-
status: :ok
-
end
-
end
-
-
def token_for(user)
-
BuilderJsonWebToken.encode(user.id)
-
end
-
end
-
end
-
module BxBlockNotifications
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
-
def current_user
-
begin
-
@current_user = AccountBlock::Account.find(@token.id)
-
rescue ActiveRecord::RecordNotFound => e
-
return render json: {errors: [
-
{message: 'Please login again.'},
-
]}, status: :unprocessable_entity
-
end
-
end
-
end
-
end
-
module BxBlockNotifications
-
class NotificationsController < ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :current_user
-
-
def index
-
@notifications = Notification.where('account_id = ?', current_user.id)
-
if @notifications.present?
-
render json: NotificationSerializer.new(@notifications, meta: {
-
message: "List of notifications."}).serializable_hash, status: :ok
-
else
-
render json: {errors: [{message: 'No notification found.'},]}, status: :ok
-
end
-
end
-
-
def show
-
@notification = Notification.find(params[:id])
-
render json: NotificationSerializer.new(@notification, meta: {
-
message: "Success."}).serializable_hash, status: :ok
-
end
-
-
def create
-
@notification = Notification.new(notification_paramas)
-
if @notification.save
-
render json: NotificationSerializer.new(@notification, meta: {
-
message: "Notification created."}).serializable_hash, status: :created
-
else
-
render json: {errors: format_activerecord_errors(@notification.errors)},
-
status: :unprocessable_entity
-
end
-
end
-
-
def update
-
@notification = Notification.find(params[:id])
-
if @notification.update(is_read: true, read_at: DateTime.now)
-
render json: NotificationSerializer.new(@notification, meta: {
-
message: "Notification marked as read."}).serializable_hash, status: :ok
-
else
-
render json: {errors: format_activerecord_errors(@notification.errors)},
-
status: :unprocessable_entity
-
end
-
end
-
-
def destroy
-
@notification = Notification.find(params[:id])
-
if @notification.destroy
-
render json: {message: "Deleted."}, status: :ok
-
else
-
render json: {errors: format_activerecord_errors(@notification.errors)},
-
status: :unprocessable_entity
-
end
-
end
-
-
private
-
-
def notification_paramas
-
params.require(:notification).permit(
-
:headings, :contents, :app_url, :account_id
-
).merge(created_by: @current_user.id)
-
end
-
-
def format_activerecord_errors(errors)
-
result = []
-
errors.each do |attribute, error|
-
result << { attribute => error }
-
end
-
result
-
end
-
end
-
end
-
module BxBlockOrderManagement
-
class AddressesController < ApplicationController
-
-
before_action :get_user, only: [:index, :create, :show, :destroy, :update]
-
before_action :fetch_address, only: [:show, :destroy, :update]
-
-
def index
-
addresses = user_delivery_addresses
-
render json: AddressesSerializer.new(addresses).serializable_hash,
-
status: :ok
-
end
-
-
def create
-
delivery_address = DeliveryAddress.new(
-
address_params.merge({ account_id: @current_user.id })
-
)
-
delivery_address.is_default = true if user_delivery_addresses.blank?
-
delivery_address.save!
-
DeliveryAddress.rest_addresses(delivery_address.id).where(
-
account_id: @current_user.id
-
).update_all(is_default: false) if delivery_address.is_default
-
render json: AddressesSerializer.new(delivery_address, serialize_options).serializable_hash,
-
message: 'Address added successfully ', status: :ok
-
end
-
-
def show
-
render json: AddressesSerializer.new(@delivery_address, serialize_options).serializable_hash,
-
status: :ok
-
end
-
-
def destroy
-
@delivery_address.destroy
-
render json: { message: 'Address deleted successfully' }, status: :ok
-
end
-
-
def update
-
@delivery_address.update!(address_params)
-
DeliveryAddress.rest_addresses(@delivery_address.id).where(
-
account_id: @current_user.id
-
).update_all(is_default: false) if @delivery_address.is_default
-
render json: AddressesSerializer.new(@delivery_address, serialize_options).serializable_hash,
-
message: 'Address updated successfully ', status: :ok
-
end
-
-
private
-
-
def user_delivery_addresses
-
@user_delivery_addresses ||= DeliveryAddress.where(account_id: @current_user.id)
-
end
-
-
def address_params
-
params.require(:address).permit(
-
:name, :flat_no, :address_type, :address, :address_line_2, :zip_code, :phone_number,
-
:latitude, :longitude, :is_default, :state, :country, :city, :landmark
-
)
-
end
-
-
def fetch_address
-
@delivery_address = DeliveryAddress.find_by(account_id: @current_user.id, id: params[:id])
-
end
-
-
def serialize_options
-
{ params: { user: @current_user } }
-
end
-
-
-
end
-
end
-
module BxBlockOrderManagement
-
class AdminController < ApplicationController
-
before_action :verify_admin_token
-
-
def delivery_address_create
-
da = BxBlockOrderManagement::DeliveryAddress.create(
-
delivery_address_params
-
)
-
render json: { delivery_address: da } if da.save
-
end
-
-
private
-
-
def delivery_address_params
-
params.require(:delivery_address).permit(
-
:account_id, :address, :address_line_2, :address_type, :address_for,
-
:name, :flat_no, :zip_code, :phone_number, :latitude, :longitude,
-
:residential, :city, :state_code, :country_code, :state, :country,
-
:is_default, :landmark
-
)
-
end
-
-
def verify_admin_token
-
unless request.headers[:admintoken] == ENV['ADMIN_API_TOKEN']
-
render json: { error: 'Invalid admin token' }
-
end
-
end
-
end
-
end
-
1
module BxBlockOrderManagement
-
1
class ApplicationController < BuilderBase::ApplicationController
-
1
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
1
before_action :validate_json_web_token
-
1
before_action :get_user
-
-
1
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
1
private
-
-
1
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
-
1
def get_user
-
20
@current_user = AccountBlock::Account.find(@token.id)
-
end
-
end
-
end
-
1
module BxBlockOrderManagement
-
1
class OrdersController < BxBlockOrderManagement::ApplicationController
-
-
1
before_action :check_order_item, only: [:show]
-
1
before_action :check_order, only: [:update_payment_source, :apply_coupon]
-
-
1
def create_order
-
2
order = BxBlockOrderManagement::Order.create!(order_params.merge(account_id: @current_user.id))
-
2
if params[:no_of_pages].to_i > find_min_limit
-
1
order.additional_pages = params[:no_of_pages].to_i - find_min_limit
-
end
-
2
if order.present? && order&.additional_pages&.present?
-
1
price_per_page = get_additional_price_per_page
-
1
get_price = BxBlockBook::Price.find_by(cover_type: order.cover_type)
-
1
order.base_price = get_price.price
-
1
order.additional_price = order.additional_pages.to_i * price_per_page.to_i
-
1
order.total = (order.additional_price + order.base_price).round(2)
-
else
-
1
get_price = BxBlockBook::Price.find_by(cover_type: order.cover_type)
-
1
order.base_price = get_price.price
-
end
-
2
if order.save
-
2
set_subtotal(order)
-
2
book = BxBlockBook::Book.find_by(id: order.book_id)
-
2
book.update(book_status: 'completed') if book
-
2
render json: OrderSerializer.new(order, serializable_options), status: 200
-
else
-
render json: { message: 'Something went wrong. Please try again' }, status: 422
-
end
-
end
-
-
1
def update_order
-
2
@book = BxBlockBook::Book.find_by(id: params[:book_id])
-
2
if @book.present?
-
1
@book.update(book_update_params)
-
end
-
2
@order = BxBlockOrderManagement::Order.find_by(id: params[:id])
-
# if
-
2
@order.update(order_params.merge(account_id: @current_user.id))
-
2
render json: OrderSerializer.new(@order, serializable_options), status: 200
-
# else
-
# render json: { message: 'Something went wrong. Please try again' }, status: 422
-
# end
-
end
-
-
1
def orders_list
-
2
orders = Order.where(
-
account_id: @current_user.id
-
).where(
-
status: params[:order_type]
-
).order(created_at: :desc)
-
2
if orders.present?
-
1
render json: OrderSerializer.new(orders).serializable_hash, status: 200
-
else
-
1
render json: { message: 'No order record found.' }, status: 200
-
end
-
end
-
-
1
def draft_order_delete
-
1
draft_orders = Order.where(account_id: @token.id).where(params[order_type: "draft"])
-
1
order = draft_orders.find_by(id: params[:id])
-
1
if order.present?
-
1
order.delete
-
1
render json: { data: {
-
order: ' Deleted Successfully'
-
}
-
}, status: :ok
-
end
-
end
-
-
1
def order_details
-
1
order = Order.find_by(id: params[:id])
-
1
render json: OrderSerializer.new(order).serializable_hash, status: 200
-
end
-
-
1
def apply_coupon
-
5
return render(json: { message: "Can't find order" }, status: 422)if @order.nil?
-
-
5
@coupon = BxBlockDiscountsoffers::Offer.find_by(code: params[:code])
-
# return render(json: { message: "Invalid coupon" }, status: 422) if @coupon.nil?
-
5
referal_user = BxBlockReferrals::ReferralUser.find_by(referral_code: params[:code])
-
5
@coupon_count = BxBlockDiscountsoffers::UserOffer.where(account: @order.account_id, code: @coupon.code) if @coupon.present?
-
-
5
shared_order = BxBlockOrderManagement::Order.find_by(sharable_code: params[:code])
-
-
5
return render(json: { message:"this Code limit is #{@coupon&.max_limit.to_i}, This code limit is Already exists" }, status: 422) unless @coupon_count&.last&.use_count.to_i < @coupon&.max_limit.to_i || referal_user.present? || shared_order.present?
-
-
5
order_count = BxBlockOrderManagement::Order.where(account_id: @current_user.id, status: 'placed').count
-
5
special_user = BxBlockDiscountsoffers::Offer.where(code: params[:code])
-
-
5
can_apply = []
-
5
if special_user.any? && special_user[0].coupon_type == "specfic_user"
-
1
special_user.each do |user|
-
1
can_apply << user.email.split(",").include?(@current_user.email)
-
end
-
end
-
-
5
return render(json: { message: "Invalid coupon" }, status: 422) if special_user.nil? || !special_user.any? && (!referal_user.present? && !shared_order.present?)
-
5
return render(json: { message: "Coupon is applicable only for vaild user" }, status: 422) if can_apply.uniq.count == 1 && can_apply.uniq.include?(false)
-
-
5
check_coupon_code(referal_user, shared_order, special_user)
-
5
return render(json: { message: @message }, status: 422) && return if @message.present?
-
-
4
return render(json: { message: "Invalid coupon" }, status: 422) if @coupon.nil?
-
4
return render(json: { message: "Coupon is applicable only for new users" }, status: 422) if order_count >= 1 && @coupon.new_users?
-
-
4
delivery_and_tax_extract = (@order.delivery_charges.to_f + @order.tax_charges.to_f).round(2)
-
4
total_amount = (@order.sub_total.to_f - delivery_and_tax_extract.to_f).round(2)
-
-
4
return render json: { message: "Keep shopping to apply the coupon" }, status: 422 if total_amount < @coupon.min_cart_value
-
4
ApplyCoupon.new(@order, @coupon, params).call
-
4
return render json: {data: {coupon: BxBlockOrderManagement::OrderSerializer.new(@order)}}, status: 200
-
end
-
-
1
def remove_coupon
-
7
@order = BxBlockOrderManagement::Order.find_by(account_id: @current_user.id, id: params[:order_id])
-
7
if @order.present?
-
6
if @order.coupon_code_id.present?
-
5
RemoveCoupon.new(@order, params).call
-
5
render json: OrderSerializer.new(@order, serializable_options), status: 200
-
else
-
1
render json: { message: "already removed coupon", status: 422 }, status: :unprocessable_entity
-
end
-
else
-
1
render json: { message: "something went wrong", status: 422 }, status: :unprocessable_entity
-
end
-
end
-
-
1
private
-
-
1
def book_update_params
-
1
params.permit(:book_title, :book_color, :title_layout, :logo_color)
-
end
-
-
# def check_order_item
-
# @order_item = OrderItem.find(params[:id])
-
# end
-
-
1
def check_order
-
5
@order = Order.find_by(account_id: @current_user.id, id: params[:order_id])
-
end
-
-
# def update_cart_total(order)
-
# @cart_response = UpdateCartValue.new(order, @current_user).call
-
# end
-
-
1
def serializable_options
-
9
{ params: { host: request.protocol + request.host_with_port } }
-
end
-
-
1
def order_params
-
4
params.permit(:no_of_pages, :book_size, :book_title, :book_color, :cover_type, :paper_type, :book_id, :title_layout, :book_url, :additional_pages)
-
end
-
-
1
def set_subtotal(order)
-
2
@delivery_charges = BxBlockBook::DeliveryCharge.first.charge
-
2
get_price = get_book_price_by_cover_type
-
2
sub_total = (get_price + @delivery_charges).round(2)
-
2
order.delivery_charges = BxBlockBook::DeliveryCharge.first.charge
-
2
order.tax_charges = (sub_total * 18 / 100).round(2)
-
2
order.amount = (sub_total + order.tax_charges).round(2)
-
2
order.sub_total = order.amount
-
2
order.payment_status = 'unpaid'
-
2
order.save
-
end
-
-
1
def get_book_price_by_cover_type
-
2
@price = BxBlockBook::Price.find_by(cover_type: params[:cover_type])
-
2
return if @price.nil?
-
2
if params[:no_of_pages].to_i >= find_min_limit
-
1
additional_pages = params[:no_of_pages].to_i - find_min_limit
-
1
total = additional_pages.to_i * get_additional_price_per_page
-
1
@price.price += total
-
else
-
1
@price.price
-
end
-
end
-
-
1
def find_min_limit
-
6
BxBlockBook::Price.find_by(cover_type: params[:cover_type]).min_limit
-
end
-
-
1
def get_additional_price_per_page
-
2
BxBlockBook::AdditionalPricePerPage.first.additional_price
-
end
-
-
1
def check_order_refer_errors(account, code, offer)
-
orders = account.orders.where(sharable_code: code)
-
used_offers = account.user_offers.where(code: code, offer_id: offer.id, applied: true)
-
refer_code_used_count = BxBlockDiscountsoffers::UserOffer.where(code: code).count
-
referral_limit_setting = BxBlockReferrals::ReferralLimitSetting.where(active: true).last
-
if orders.any?
-
@message = "You are not authorized to use this code"
-
elsif referral_limit_setting && (refer_code_used_count >= referral_limit_setting.max_order_refers)
-
@message = "This offer can use by only #{referral_limit_setting.max_order_refers} users"
-
elsif used_offers.any?
-
@message = "Already used this code"
-
end
-
@message
-
end
-
-
1
def check_coupon_code(referal_user, shared_order, special_user)
-
5
if referal_user
-
1
check_refer_errors(referal_user)
-
4
elsif shared_order
-
@coupon = BxBlockDiscountsoffers::Offer.find_by(coupon_type: 'share_order_code', active: true)
-
check_order_refer_errors(@current_user, params[:code], @coupon)
-
4
elsif special_user[0].coupon_type == "specfic_user"
-
# @coupon = BxBlockDiscountsoffers::Offer.find_by(coupon_type: 'specfic_user', active: true)
-
1
check_order_special_errors(params[:code], @coupon)
-
else
-
3
@coupon = BxBlockDiscountsoffers::Offer.find_by(discount: params[:discount], code: params[:code])
-
end
-
end
-
-
1
def check_order_special_errors(code, coupon)
-
1
if (coupon.coupon_type).present?
-
1
coupon = BxBlockDiscountsoffers::Offer.find_by(coupon_type: 'specfic_user', active: false)
-
# coupon.update(code: params[:code]) if coupon.present?
-
1
(@message = "Code is not activated") && return if coupon&.active == false
-
else
-
@message = "You are not use this code"
-
end
-
1
if @message.present?
-
return @message
-
else
-
1
return coupon
-
end
-
end
-
-
1
def check_refer_errors(referal_user)
-
1
if @current_user.referral_user.referral_by == params[:code]
-
@coupon = BxBlockDiscountsoffers::Offer.find_by(coupon_type: 'referral', active: true)
-
@coupon.update(code: params[:code]) if @coupon.present?
-
@referral = BxBlockReferrals::ReferralUser.find_by(account_id: @current_user.id)
-
referral_limit = BxBlockReferrals::ReferralLimitSetting.last.max_order_refers
-
@order_account = AccountBlock::Account.find_by(id: @order.account_id)
-
(@message = "Code is already used") && return unless @referral.code_used.to_i < 1
-
(@message = "Code Is Expried") unless referal_user.referal_count.to_i < referral_limit
-
(@message = "Code is not activated") && return if @coupon.nil?
-
else
-
1
@message = "You are not use this code"
-
end
-
1
if @message.present?
-
1
return @message
-
else
-
return @coupon
-
end
-
end
-
end
-
end
-
module BxBlockOrderManagement
-
class ShiprocketController < BxBlockOrderManagement::ApplicationController
-
before_action :find_order, only: [:download_invoice, :create, :cancel_order, :get_order, :generate_manifest, :print_manifest, :generate_label, :generate_invoice, :return_order, :track_order]
-
-
def create
-
@response = []
-
ship_rocket = BxBlockOrderManagement::Shiprocket.new
-
if (@order.address&.share_with_family_member == true)
-
new_order_ids = []
-
new_order = clone_order_and_address(@order)
-
unless @order.ship_rocket_order_id.present?
-
new_order_ids = [@order, new_order]
-
new_order_ids.each do |order|
-
if ship_rocket.authorize
-
response = ship_rocket.post_order(order.id)
-
json_response = JSON.parse(response)
-
if json_response['errors'].present?
-
@response << { error: request.referer, message: json_response['errors'].values.flatten.join(',') }
-
else
-
order.update_shipment_details(json_response)
-
if order.order_items.present?
-
order.order_items.each do |order_item|
-
tracking = BxBlockOrderManagement::Tracking.find_or_create_by(date: DateTime.current, status: json_response['status'].to_s.downcase )
-
order_item.order_trackings.create(tracking_id: tracking.id)
-
end
-
end
-
SystemMailer.order_placed_info(order, json_response).deliver!
-
@response << { reponse: json_response, message: request.referer, notice: 'Shipping request has been sent to ShipRocket successfully.' }
-
end
-
else
-
return shiprocket_error_response(request)
-
end
-
end
-
end
-
else
-
puts "======================= create shiprocket order api ================"
-
if ship_rocket.authorize
-
puts "======================= loged in into shiprocket ================"
-
response = ship_rocket.post_order(@order.id)
-
json_response = JSON.parse(response)
-
if json_response['errors'].present?
-
@response << { error: request.referer, message: json_response['errors'].values.flatten.join(',') }
-
else
-
puts "======================= shiprocket order created ================"
-
@order.update_shipment_details(json_response)
-
puts "======================= updated shipment details in shiprocket ================"
-
if @order.order_items.present?
-
@order.order_items.each do |order_item|
-
tracking = BxBlockOrderManagement::Tracking.find_or_create_by(date: DateTime.current, status: json_response['status'].to_s.downcase )
-
order_item.order_trackings.create(tracking_id: tracking.id)
-
end
-
end
-
SystemMailer.order_placed_info(@order, json_response).deliver!
-
@response << { reponse: json_response, message: request.referer, notice: 'Shipping request has been sent to ShipRocket successfully.' }
-
end
-
else
-
puts "======================= Got error from shiprocket ================"
-
return shiprocket_error_response(request)
-
end
-
end
-
render json: { response: @response.blank? ? @response << { notice: 'Order already in system Shipping request was sent to ShipRocket successfully.'} : @response }
-
end
-
-
def cancel_order
-
ship_rocket = BxBlockOrderManagement::Shiprocket.new
-
if ship_rocket.authorize
-
response = ship_rocket.cancel_order(@order.id)
-
json_response = JSON.parse(response)
-
if json_response['errors'].present?
-
render json: { error: request.referer, message: json_response['errors'].values.flatten.join(','), status: 422 }, status: :unprocessable_entity
-
else
-
order.update_shipment_details(json_response)
-
SystemMailer.order_canceled_info(order, json_response).deliver!
-
render json: { message: json_response["message"], status: json_response["status_code"] }
-
end
-
else
-
shiprocket_error_response(request)
-
end
-
end
-
-
def get_order
-
ship_rocket = BxBlockOrderManagement::Shiprocket.new
-
if ship_rocket.authorize
-
response = ship_rocket.get_order(@order.id)
-
shiprocket_json_response(response)
-
else
-
shiprocket_error_response(request)
-
end
-
end
-
-
def generate_manifest
-
ship_rocket = BxBlockOrderManagement::Shiprocket.new
-
if ship_rocket.authorize
-
response = ship_rocket.generate_manifest(@order.id)
-
shiprocket_json_response(response)
-
else
-
shiprocket_error_response(request)
-
end
-
end
-
-
def print_manifest
-
ship_rocket = BxBlockOrderManagement::Shiprocket.new
-
if ship_rocket.authorize
-
response = ship_rocket.print_manifest(@order.id)
-
shiprocket_json_response(response)
-
else
-
shiprocket_error_response(request)
-
end
-
end
-
-
def generate_label
-
ship_rocket = BxBlockOrderManagement::Shiprocket.new
-
if ship_rocket.authorize
-
response = ship_rocket.generate_label(@order.id)
-
shiprocket_json_response(response)
-
else
-
shiprocket_error_response(request)
-
end
-
end
-
-
def generate_invoice
-
ship_rocket = BxBlockOrderManagement::Shiprocket.new
-
if ship_rocket.authorize
-
response = ship_rocket.generate_invoice(@order.id)
-
shiprocket_json_response(response)
-
else
-
shiprocket_error_response(request)
-
end
-
end
-
-
def download_invoice
-
ship_rocket = BxBlockOrderManagement::Shiprocket.new
-
if ship_rocket.authorize
-
response = ship_rocket.generate_invoice(@order.id)
-
response_data = JSON.parse(response)
-
file = URI.open(response_data['invoice_url'])
-
# data = File.read(file, encoding: 'ASCII-8BIT')
-
send_data(file, :disposition => "inline", :type => "application/pdf")
-
else
-
shiprocket_error_response(request)
-
end
-
end
-
-
def return_order
-
ship_rocket = BxBlockOrderManagement::Shiprocket.new
-
if ship_rocket.authorize
-
response = ship_rocket.return_order(@order.id)
-
shiprocket_json_response(response)
-
else
-
shiprocket_error_response(request)
-
end
-
end
-
-
def track_order
-
ship_rocket = BxBlockOrderManagement::Shiprocket.new
-
if ship_rocket.authorize
-
response = ship_rocket.track_order(@order.id)
-
shiprocket_json_response(response)
-
else
-
shiprocket_error_response(request)
-
end
-
end
-
-
private
-
-
def find_order
-
@order = BxBlockOrderManagement::Order.find_by(id: params[:id])
-
unless @order.present?
-
render json: {
-
status: 404,
-
message: 'Order not found with this id'
-
}, status: :not_found
-
end
-
end
-
-
def shiprocket_error_response(request)
-
render json: { message: request.referer, notice: 'Something went wrong, while shiping with Ship Rocket' }
-
end
-
-
def shiprocket_json_response(response)
-
json_response = JSON.parse(response)
-
if json_response['errors'].present?
-
render json: { error: request.referer, message: json_response['errors'].values.flatten.join(','), status: 422 },
-
status: :unprocessable_entity
-
else
-
render json: { message: json_response }
-
end
-
end
-
-
def clone_order_and_address(order)
-
if order.order_child_id.eql?(nil)
-
@order.order_child_id = @order.id
-
@order.quantity = 1
-
@order.amount = (@order.amount / 2)
-
@order.sub_total = (@order.sub_total / 2)
-
@order.tax_charges = (@order.tax_charges.to_f/ 2)
-
@order.delivery_charges = (@order.delivery_charges.to_i / 2)
-
@order.additional_pages = (@order.additional_pages.to_i / 2)
-
@order.additional_price = (@order.additional_price.to_i / 2)
-
@order.total = (@order.total.to_f / 2)
-
@order.base_price = (@order.base_price.to_i / 2)
-
@order.applied_discount = (@order&.applied_discount.to_i / 2)
-
@order.save
-
new_order = @order.dup
-
new_order.order_child_id = @order.id
-
new_order.quantity = 1
-
new_order.save
-
address = @order.address.dup
-
shared_address = @order.address.shared_address
-
address.phone_number = shared_address.phone_number
-
address.full_name = shared_address.full_name
-
address.pincode = shared_address.pincode
-
address.city = shared_address.city
-
address.landmark = shared_address.landmark
-
address.state = shared_address.state
-
address.share_with_family_member = false
-
address.address = shared_address.address1
-
address.order_id = new_order.id
-
address.save
-
return new_order
-
else
-
return BxBlockOrderManagement::Order.where(order_child_id: order.id).last
-
end
-
end
-
end
-
end
-
module BxBlockOrderManagement
-
class WebhookController < ApplicationController
-
def shiprocket_order_updates
-
puts "#{params["awb"]}"
-
end
-
end
-
end
-
module BxBlockOrdersummary
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
1
module BxBlockOrdersummary
-
1
class OrderSummaryController < ApplicationController
-
1
before_action :check_order, only: [:get_order_details, :order_x2, :update_quantity, :add_gift_note, :get_book_url_details, :create_subtotal]
-
-
1
def create
-
1
@order_summary = BxBlockOrdersummary::OrderSummary.create(order_summary_params)
-
1
if @order_summary.save
-
1
return success_response(@order_summary, :created)
-
else
-
render json: { message: "something went wrong", status: 422 }, status: :unprocessable_entity
-
end
-
end
-
-
# when share with famliy member is true on address create
-
1
def order_x2
-
# @order = BxBlockOrderManagement::Order.find_by(id: params[:order_id])
-
2
if @order.present?
-
1
if (@order&.address&.share_with_family_member == true)
-
@order.update(quantity: 2)
-
@order.amount = (@order.amount * 2)
-
@order.sub_total = (@order.sub_total * 2)
-
@order.tax_charges = (@order.tax_charges.to_i * 2)
-
@order.delivery_charges = (@order.delivery_charges.to_i * 2)
-
@order.save
-
render json: BxBlockOrderManagement::OrderSerializer.new(@order).serializable_hash, status: :ok
-
else
-
1
@order.update(quantity: 1)
-
1
@order.amount = (@order.amount / 2)
-
1
@order.sub_total = (@order.sub_total / 2)
-
1
@order.tax_charges = (@order.tax_charges.to_i / 2)
-
1
@order.delivery_charges = (@order.delivery_charges.to_i / 2)
-
1
@order.save
-
1
render json: BxBlockOrderManagement::OrderSerializer.new(@order).serializable_hash, status: :ok
-
end
-
else
-
1
render json: { message: "order not present", status: 422 }, status: :unprocessable_entity
-
end
-
end
-
-
1
def get_order_details
-
# @order_details = BxBlockOrderManagement::Order.find_by(id: params[:order_id])
-
2
if @order.present?
-
1
render json: BxBlockOrderManagement::OrderSerializer.new(@order).serializable_hash, status: :ok
-
else
-
1
render json: { message: "something went wrong", status: 422 }, status: :unprocessable_entity
-
end
-
end
-
-
1
def update_quantity
-
# @order = BxBlockOrderManagement::Order.find_by(id: params[:order_id])
-
2
get_delivery_charge = @order.delivery_charges.to_i
-
2
if @order.present?
-
2
if @order.coupon_code_id.present?
-
1
coupon = BxBlockDiscountsoffers::Offer.find_by(id: @order.coupon_code_id)
-
1
calc_total = params[:amount].to_i * params[:quantity].to_i
-
1
get_taxes = ((params[:amount].to_i * params[:quantity].to_i) * 18 / 100)
-
-
1
if calc_total > coupon.min_cart_value
-
discount = coupon.discount_type == "percentage" ? ((calc_total * coupon.discount) / 100) : coupon_code.discount # 4400 * 25.0 / 100
-
sb_total = calc_total - discount
-
@order.update(sub_total: sb_total + get_delivery_charge + get_taxes)
-
@order.update(quantity: params[:quantity])
-
@order.update(tax_charges: get_taxes)
-
@order.update(applied_discount: discount)
-
-
render json: { quantity: @order.quantity, sub_total: @order.sub_total, applied_discount: @order.applied_discount, tax_charges: @order.tax_charges }
-
else
-
1
@order.update(coupon_code_id: nil)
-
1
@order.update(applied_discount: 0.0)
-
1
@order.quantity = params[:quantity]
-
1
@order.update(tax_charges: get_taxes)
-
1
calc_total = (params[:amount].to_i * params[:quantity].to_i + get_delivery_charge + get_taxes)
-
1
@order.sub_total = calc_total.to_d
-
1
@order.save
-
-
1
render json: { quantity: @order.quantity, sub_total: @order.sub_total, applied_discount: @order.applied_discount, tax_charges: @order.tax_charges }
-
end
-
else
-
1
get_taxes = ((params[:amount].to_i * params[:quantity].to_i) * 18 / 100)
-
1
calc_total = ((params[:amount].to_i * params[:quantity].to_i) + get_taxes + get_delivery_charge)
-
-
1
@order.quantity = params[:quantity]
-
1
@order.sub_total = calc_total.to_d
-
1
@order.tax_charges = get_taxes
-
1
@order.save
-
-
1
render json: { quantity: @order.quantity, sub_total: @order.sub_total, applied_discount: @order.applied_discount, tax_charges: @order.tax_charges }
-
end
-
else
-
render json: { message: "Order not found with this id", status: 422 }, status: :unprocessable_entity
-
end
-
end
-
-
1
def add_gift_note
-
# @order = BxBlockOrderManagement::Order.find_by(id: params[:order_id])
-
2
if @order.present?
-
1
@order.update(gift_note: params[:gift_note])
-
1
render json: BxBlockOrderManagement::OrderSerializer.new(@order).serializable_hash, status: :ok
-
else
-
1
render json: { message: "something went wrong", status: 422 }, status: :unprocessable_entity
-
end
-
end
-
-
1
def create_subtotal
-
# @order = BxBlockOrderManagement::Order.find_by(id: params[:order_id])
-
if @order.present?
-
order_price = @order.price
-
get_delivery_charge = BxBlockBook::DeliveryCharge.first.charge
-
subtotal = order_price + get_delivery_charge
-
-
render json: { subtotal: subtotal, status: 200 }, status: :ok
-
else
-
render json: { message: "not order found with this id", status: 404 }, status: :not_found
-
end
-
end
-
-
1
def get_book_url_details
-
# @order_details = BxBlockOrderManagement::Order.find_by(id: params[:order_id])
-
2
if @order.present?
-
1
render json: {data: [{book_url: @order.book_url},]}, status: :ok
-
else
-
1
render json: { message: "Please Enter Vaild Order Id"}, status: :unprocessable_entity
-
end
-
end
-
-
1
private
-
-
1
def check_order
-
10
@order = BxBlockOrderManagement::Order.find_by(id: params[:order_id])
-
end
-
-
1
def order_summary_params
-
1
params.permit(:quantity, :gift_note, :discount_code, :order_subtotal, :book_id, :delivery_charge, :book_size, :cover_type, :order_total, :order_id)
-
end
-
-
1
def success_response(order_summary, status = 200)
-
1
render json: BxBlockOrdersummary::OrderSummarySerializer.new(order_summary).
-
serializable_hash,
-
status: status
-
end
-
end
-
end
-
module BxBlockPaymentAdmin
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
module BxBlockPaymentAdmin
-
class PaymentAdminController < ApplicationController
-
def index
-
if params[:type] == "credit"
-
@payments = BxBlockPaymentAdmin::PaymentAdmin.where("account_id = ?", @token.id )
-
end
-
if params[:type] == "debit"
-
@payments = BxBlockPaymentAdmin::PaymentAdmin.where("current_user_id = ?", @token.id )
-
end
-
return render json: {data: @payments} , status: :ok
-
end
-
-
def show
-
@payments = BxBlockPaymentAdmin::PaymentAdmin.find(params[:id])
-
return render json: {data: @payments} , status: :ok
-
end
-
end
-
end
-
module BxBlockPaymentRazorpay
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
require 'digest'
-
-
module BxBlockPaymentRazorpay
-
class RazorpaysController < BxBlockPaymentRazorpay::ApplicationController
-
-
before_action :create_order_items, only: [:create]
-
-
def create
-
order = BxBlockOrderManagement::Order.find(params[:order_id])
-
-
if order.present?
-
puts "======================= started payment for order: #{order.id} ================"
-
amount = (order.sub_total * 100 ).to_i
-
receipt = Digest::MD5.hexdigest(order.order_number.to_s)
-
begin
-
puts "======================= creating payment for order: #{order.id} ================"
-
razorpay_order = Payment.create(amount, 'INR', receipt)
-
if razorpay_order.status == 'created'
-
puts "======================= created payment for order: #{order.id} ================"
-
order.update(razorpay_order_id: razorpay_order.id)
-
# order.update(payment_status: 'paid')
-
# order.update(placed_at: Time.now())
-
#order.update(placed_at: Time.now + Time.zone_offset('IST'))
-
order_status_id = BxBlockOrderManagement::OrderStatus.find_or_create_by(
-
status: 'confirmed', event_name: 'confirm_order'
-
)
-
-
render json: BxBlockOrderManagement::OrderSerializer.new(order).serializable_hash,
-
status: :ok
-
end
-
# SystemMailer.order_create_info(order).deliver!
-
# SystemMailer.payment_done_info(order).deliver!
-
rescue Exception => e
-
puts "======================= exception for creating payment for order: #{order.id} ================"
-
order.update(payment_status: 'failed')
-
-
SystemMailer.payment_failed_info(order).deliver!
-
render json: { message: e }
-
end
-
else
-
render json: { success: false, errors: 'Order Not Found.' },
-
status: :not_found
-
end
-
end
-
-
def order_details
-
if params[:razorpay_order_id].present?
-
begin
-
details = Payment.order_details(params[:razorpay_order_id])
-
-
render json: {
-
success: true,
-
details: OrderDetailsSerializer.new(details).serializable_hash
-
}
-
rescue Exception => e
-
render json: { message: e }
-
end
-
else
-
render json: { error: { message: 'order_number param required' } },
-
status: :not_found
-
end
-
end
-
-
def verify_signature
-
#create record in transactions table
-
begin
-
puts "======================= rezorpay verification process ================"
-
verify_result = Payment.verify(
-
params[:razorpay_order_id],
-
params[:razorpay_payment_id],
-
params[:razorpay_signature]
-
)
-
-
puts "======================= #{verify_result} ================"
-
-
order = BxBlockOrderManagement::Order.find_by(razorpay_order_id: params[:razorpay_order_id])
-
order.update(status: 'in_transit', payment_status: 'paid', placed_at: Time.now())
-
-
orders_transaction = order.order_transaction
-
-
if orders_transaction.present?
-
orders_transaction.update(status: 'in_transit',
-
razorpay_payment_id: params[:razorpay_payment_id],
-
razorpay_signature: params[:razorpay_signature]
-
)
-
end
-
# SystemMailer.payment_verified_info(order, order.order_transaction).deliver!
-
-
puts "======================= payment captured and updated in order ================"
-
-
render json: { success: verify_result }, status: :ok
-
-
rescue Exception => e
-
puts "======================= Exception in capturing payment ================"
-
render json: { message: e }
-
end
-
end
-
-
def capture
-
order = BxBlockOrderManagement::Order.find(params[:order_id])
-
-
if order.present?
-
amount = (order.sub_total.to_f * 100 )
-
begin
-
response = Payment.capture(params[:payment_id], amount)
-
-
render json: CaptureResponseSerializer.new(response).serializable_hash, status: :ok
-
rescue Exception => e
-
render json: { message: e }
-
end
-
else
-
render json: { success: false, errors: 'Order Not Found.' },
-
status: :not_found
-
end
-
end
-
-
private
-
-
def create_order_items
-
order = BxBlockOrderManagement::Order.find(params[:order_id])
-
if order.present?
-
@order_items = order.order_items.build(order_id: order.id, quantity: order.quantity, unit_price: order.base_price.to_f + order.delivery_charges.to_f + order.additional_price.to_f - order&.applied_discount.to_f)
-
@order_items.save
-
else
-
render json: { success: false, errors: 'Order Not Found.' },
-
status: :not_found
-
end
-
end
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockPlan
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
before_action :validate_json_web_token
-
end
-
end
-
# frozen_string_literal: true
-
-
module BxBlockPlan
-
class PlansController < ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
before_action :validate_json_web_token, except: [:index]
-
-
def index
-
plans = BxBlockPlan::Plan.all
-
if plans.present?
-
render json: { plans: plans, message: 'Successfully Loaded' }
-
else
-
render json: { data: [] },
-
status: :ok
-
end
-
end
-
end
-
end
-
module BxBlockPosts
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
-
def current_user
-
@current_user ||= AccountBlock::Account.find(@token.id) if @token.present?
-
end
-
-
def check_account_activated
-
account = AccountBlock::Account.find_by(id: current_user.id)
-
unless account.activated
-
render json: { error: {
-
message: "Account has been not activated"}
-
}, status: :unprocessable_entity
-
end
-
end
-
end
-
end
-
module BxBlockPosts
-
class PostsController < ApplicationController
-
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
before_action :check_image_video_formate, only: [:create, :update]
-
before_action :check_account_activated
-
-
def index
-
posts = BxBlockPosts::Post.all
-
if posts.present?
-
render json: PostSerializer.new(posts, params: {current_user: current_user}).serializable_hash
-
else
-
render json: {data: []},
-
status: :ok
-
end
-
end
-
-
def create
-
service = BxBlockPosts::Create.new(current_user, post_params)
-
new_post = service.execute
-
if new_post.persisted?
-
new_post.upload_post_images(params[:data][:attributes][:images]) if params[:data][:attributes][:images].present?
-
-
render json: PostSerializer.new(new_post).serializable_hash,
-
status: :ok
-
else
-
render json: ErrorSerializer.new(new_post).serializable_hash,
-
status: :unprocessable_entity
-
end
-
end
-
-
def show
-
post = BxBlockPosts::Post.find_by(id: params[:id])
-
-
return render json: {errors: [
-
{Post: 'Not found'},
-
]}, status: :not_found if post.blank?
-
json_data = PostSerializer.new(post, params: {current_user: current_user}).serializable_hash
-
render json: json_data
-
end
-
-
def update
-
post = BxBlockPosts::Post.find_by(id: params[:id], account_id: current_user.id)
-
-
return render json: {errors: [
-
{Post: 'Not found'},
-
]}, status: :not_found if post.blank?
-
-
post = BxBlockPosts::Update.new(post, post_params).execute
-
-
if post.persisted?
-
post.upload_post_images(params[:data][:attributes][:images]) if params[:data][:attributes][:images].present?
-
render json: PostSerializer.new(post, params: {current_user: current_user}).serializable_hash
-
else
-
render json: {errors: format_activerecord_errors(post.errors)},
-
status: :unprocessable_entity
-
end
-
end
-
-
def search
-
@posts = Post.where('description ILIKE :search', search: "%#{search_params[:query]}%")
-
render json: PostSerializer.new(@posts, params: {current_user: current_user}).serializable_hash, status: :ok
-
end
-
-
def destroy
-
post = BxBlockPosts::Post.find_by(id: params[:id], account_id: current_user.id)
-
return if post.nil?
-
if post.destroy
-
render json: {}, status: :ok
-
else
-
render json: ErrorSerializer.new(post).serializable_hash,
-
status: :unprocessable_entity
-
end
-
end
-
-
private
-
-
def post_params
-
params.require(:data)[:attributes].permit(
-
:name, :description, :body, :category_id, :location,
-
tag_list: [],
-
images: [],
-
location_attributes: [:id, :address, :_destroy]
-
)
-
end
-
-
def search_params
-
params.permit(:query)
-
end
-
-
def format_activerecord_errors(errors)
-
result = []
-
errors.each do |attribute, error|
-
result << { attribute => error }
-
end
-
result
-
end
-
-
def check_image_video_formate
-
return if params[:data][:attributes][:images].blank?
-
image_formats = %w(image/jpeg image/jpg image/png)
-
video_formats = %w(video/mp4 video/mov video/wmv video/flv video/avi video/mkv video/webm)
-
params[:data][:attributes][:images].each do |image_data|
-
content_type = image_data[:content_type].to_s.split('/').first
-
if image_formats.exclude?(image_data[:content_type]) && content_type == 'image'
-
render json: {errors: ["The image is unsupported type, supported formates are #{image_formats}"]},
-
status: :unprocessable_entity
-
elsif video_formats.exclude?(image_data[:content_type]) && content_type == 'video'
-
render json: {errors: ["The video is unsupported type, supported formates are #{video_formats}"]},
-
status: :unprocessable_entity
-
end
-
end
-
end
-
end
-
end
-
module BxBlockPrivacySettings
-
class AboutUsController < ApplicationController
-
skip_before_action :validate_json_web_token, only: %i[show], raise: false
-
-
def show
-
about_us = BxBlockAdmin::AboutUs.last
-
if about_us.present?
-
render json: BxBlockPrivacySettings::AboutUsSerializer.new(about_us).serializable_hash
-
else
-
render json: {data: []}, status: :ok
-
end
-
end
-
end
-
end
-
module BxBlockPrivacySettings
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
-
def current_user
-
@current_user ||= AccountBlock::Account.find(@token.id) if @token.present?
-
end
-
-
def check_account_activated
-
account = AccountBlock::Account.find_by(id: current_user.id)
-
unless account.activated
-
render json: { error: {
-
message: "Account has been not activated"}
-
}, status: :unprocessable_entity
-
end
-
end
-
end
-
end
-
module BxBlockPrivacySettings
-
class PrivacyPoliciesController < ApplicationController
-
skip_before_action :validate_json_web_token, only: %i[show], raise: false
-
-
def show
-
privacy_policy = BxBlockAdmin::PrivacyPolicy.last
-
if privacy_policy.present?
-
render json: BxBlockPrivacySettings::PrivacyPolicySerializer.new(privacy_policy).serializable_hash
-
else
-
render json: {data: []}, status: :ok
-
end
-
end
-
-
end
-
end
-
module BxBlockPrivacySettings
-
class QuestionAnswerController < ApplicationController
-
skip_before_action :validate_json_web_token, only: %i[index], raise: false
-
before_action :get_question_answer, only: [:show, :update, :destroy]
-
-
def index
-
-
@question_answers = BxBlockHelpCentre::QuestionAnswer.all.order('created_at DESC')
-
if @question_answers.present?
-
render json: BxBlockHelpCentre::QuestionAnswerSerializer.new(
-
@question_answers, meta: { message: 'List of question answers.' }
-
).serializable_hash, status: :ok
-
else
-
render json: {
-
errors: [ { message: 'No question found.' },]
-
}, status: :unprocessable_entity
-
end
-
end
-
-
def show
-
render json: BxBlockHelpCentre::QuestionAnswerSerializer.new(
-
@question_answer,
-
meta: { success: true, message: "Question Answer." }
-
).serializable_hash, status: :ok
-
end
-
-
def create
-
@question_answer = BxBlockHelpCentre::QuestionAnswer.new(jsonapi_deserialize(params))
-
if @question_answer.save
-
render json: BxBlockHelpCentre::QuestionAnswerSerializer.new(
-
@question_answer,
-
meta: { message: "Question Answer created." }
-
).serializable_hash, status: :created
-
else
-
render json: { errors: format_activerecord_errors(@question_answer.errors) },
-
status: :unprocessable_entity
-
end
-
end
-
-
def update
-
if @question_answer.update(jsonapi_deserialize(params))
-
render json: BxBlockHelpCentre::QuestionAnswerSerializer.new(
-
@question_answer,
-
meta: { message: "Question Answer updated." }
-
).serializable_hash, status: :ok
-
else
-
render json: { errors: format_activerecord_errors(@question_answer.errors) },
-
status: :unprocessable_entity
-
end
-
end
-
-
def destroy
-
if @question_answer.destroy
-
render json: { message: "Question answer deleted." }, status: :ok
-
else
-
render json: {
-
errors: [ { message: 'Question answer did not delete.' } ]
-
}, status: :unprocessable_entity
-
end
-
end
-
def get_question_answer
-
@question_answer = BxBlockHelpCentre::QuestionAnswer.find_by(id: params[:id])
-
return render json: {
-
errors: [ { message: 'Question not found.' }, ]
-
}, status: :unprocessable_entity unless @question_answer.present?
-
end
-
end
-
end
-
module BxBlockPrivacySettings
-
class ReturnAndRefundController < ApplicationController
-
skip_before_action :validate_json_web_token, only: %i[show], raise: false
-
-
def show
-
return render json: { message: "Content not found" }, status: :not_found unless BxBlockAdmin::ReturnAndRefundPolicy.all.present?
-
serializer = BxBlockPrivacySettings::PrivacyPolicySerializer.new(BxBlockAdmin::ReturnAndRefundPolicy.first)
-
render json: serializer.serializable_hash,
-
status: :ok
-
end
-
end
-
end
-
module BxBlockPrivacySettings
-
class TermsAndConditionsController < ApplicationController
-
skip_before_action :validate_json_web_token, only: %i[show], raise: false
-
-
def show
-
return render json: { message: "Content not found" }, status: :not_found unless BxBlockAdmin::TermsAndCondition.all.present?
-
serializer = TermsAndConditionsSerializer.new(BxBlockAdmin::TermsAndCondition.first)
-
render json: serializer.serializable_hash,
-
status: :ok
-
end
-
end
-
end
-
module BxBlockProfile
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
before_action :validate_json_web_token
-
# serialization_scope :view_context
-
-
private
-
-
def format_activerecord_errors(errors)
-
result = []
-
errors.each do |attribute, error|
-
result << { attribute => error }
-
end
-
result
-
end
-
end
-
end
-
module BxBlockProfile
-
class AwardsController < ApplicationController
-
-
def create
-
@profile = current_user.profiles.find_by(profile_role:"jobseeker")
-
-
if @profile.present?
-
@awards = BxBlockProfile::Award.new(award_params.merge({profile_id: @profile.id}))
-
-
if @awards.save
-
render json: BxBlockProfile::AwardSerializer.new(@awards
-
).serializable_hash, status: :created
-
else
-
render json: {
-
errors: format_activerecord_errors(@awards.errors)
-
}, status: :unprocessable_entity
-
end
-
else
-
return render json: {errors: [
-
{profile: 'No jobseeker profile exist for this account'},
-
]}, status: :unprocessable_entity
-
end
-
end
-
-
def index
-
@awards = BxBlockProfile::Award.all
-
if @awards.present?
-
render json: BxBlockProfile::AwardSerializer.new(@awards, meta: {
-
message: "Awards List"
-
}).serializable_hash, status: :ok
-
else
-
render json:{meta: {message: "Record not found."}}
-
end
-
end
-
-
def show
-
award = BxBlockProfile::Award.find_by({id: params[:id]})
-
-
if award.present?
-
render json: BxBlockProfile::AwardSerializer.new(award, meta: {
-
message: "here is the profile with the given id"
-
}).serializable_hash, status: :ok
-
-
else
-
render json:{meta: {message: "Record not found."}}
-
end
-
end
-
-
def destroy
-
award = BxBlockProfile::Award.find_by({id: params[:id]})
-
if award&.destroy
-
render json:{ meta: { message: "Award Removed"}}
-
else
-
render json:{meta: {message: "Record not found."}}
-
end
-
end
-
-
private
-
-
def current_user
-
@account = AccountBlock::Account.find_by(id: @token.id)
-
end
-
-
def award_params
-
params.require(:award).permit \
-
:title,
-
:associated_with,
-
:issuer,
-
:issue_date,
-
:description,
-
:make_public
-
end
-
end
-
end
-
module BxBlockProfile
-
class CareerExperiencesController < ApplicationController
-
def index
-
@career_experiences = CareerExperience.all
-
render json: CareerExperienceSerializer.new(@career_experiences, meta: {
-
message: "Successfully Loaded"
-
}).serializable_hash, status: :ok
-
end
-
-
def create
-
@profile = current_user.profiles.find_by(profile_role:"jobseeker")
-
-
if @profile.present?
-
@career_experience = BxBlockProfile::CareerExperience.new(
-
career_experience_params.merge({ profile_id: @profile.id} ))
-
if @career_experience.save
-
create_industry && create_employment_type && create_system_experience
-
render json: BxBlockProfile::CareerExperienceSerializer.new(@career_experience
-
).serializable_hash, status: :created
-
else
-
render json: {
-
errors: format_activerecord_errors(@career_experience.errors)
-
}, status: :unprocessable_entity
-
end
-
else
-
return render json: {errors: [
-
{profile: 'No jobseeker profile exist for this account'},
-
]}, status: :unprocessable_entity
-
end
-
end
-
-
def show
-
ce = BxBlockProfile::CareerExperience.find_by({id: params[:id]})
-
-
if ce.present?
-
render json: CareerExperienceSerializer.new(ce, meta: {
-
message: "Career Experience"
-
}).serializable_hash, status: :ok
-
-
else
-
render json:{meta: {message: "Record not found."}}
-
end
-
end
-
-
def update
-
career_experience = BxBlockProfile::CareerExperience.find_by(id: params[:id])
-
if career_experience.present?
-
career_experience.update(career_experience_params)
-
render json: CareerExperienceSerializer.new(career_experience, meta: {
-
message: "Career Experience updated successfully"
-
}).serializable_hash, status: :ok
-
else
-
render json: {
-
errors: format_activerecord_errors(career_experience.errors)
-
}, status: :unprocessable_entity
-
end
-
end
-
-
def destroy
-
career_experience = BxBlockProfile::CareerExperience.find_by(id: params[:id])
-
if career_experience&.destroy
-
render json:{ meta: { message: "Career Experience Removed"}}
-
else
-
render json:{meta: {message: "Record not found."}}
-
end
-
end
-
-
private
-
-
def current_user
-
@account = AccountBlock::Account.find_by(id: @token.id)
-
end
-
-
def career_experience_params
-
params.require(:career_experience).permit \
-
:id,
-
:job_title,
-
:start_date,
-
:end_date,
-
:company_name,
-
:description,
-
:make_key_achievements_public,
-
:current_salary,
-
:currently_working_here,
-
:notice_period,
-
:notice_period_end_date,
-
add_key_achievements: []
-
end
-
-
def create_industry
-
industry = Industry.where(industry_name: params[:industry_name]).first
-
if industry.present?
-
CareerExperienceIndustry.create(career_experience_id: @career_experience.id, industry_id: industry.id)
-
else
-
industry = Industry.create(industry_name: params[:industry_name])
-
CareerExperienceIndustry.create(career_experience_id: @career_experience.id, industry_id: industry.id)
-
end
-
end
-
-
def create_employment_type
-
employment_type = EmploymentType.where(employment_type_name: params[:employment_type_name]).first
-
if employment_type.present?
-
CareerExperienceEmploymentType.create(career_experience_id: @career_experience.id,
-
employment_type_id: employment_type.id)
-
else
-
employment_type = EmploymentType.create(employment_type_name: params[:employment_type_name])
-
CareerExperienceEmploymentType.create(career_experience_id: @career_experience.id,
-
employment_type_id: employment_type.id)
-
end
-
end
-
-
def create_system_experience
-
system_experience = SystemExperience.where(system_experience: params[:system_experience]).first
-
if system_experience.present?
-
CareerExperienceSystemExperience.create(career_experience_id: @career_experience.id,
-
system_experience_id: system_experience.id)
-
else
-
system_experience = SystemExperience.create(system_experience: params[:system_experience])
-
CareerExperienceSystemExperience.create(career_experience_id: @career_experience.id,
-
system_experience_id: system_experience.id)
-
end
-
end
-
-
end
-
end
-
module BxBlockProfile
-
class ChangePhoneValidationsController < ApplicationController
-
def create
-
validator = ChangePhoneValidator
-
.new(@token.id, create_params[:new_phone_number])
-
-
if validator.valid?
-
render json: {
-
messages: [{
-
profile: 'Phone number change is valid',
-
}],
-
}, status: :created
-
else
-
errors = validator.errors.full_messages
-
render :json => {:errors => [{:profile => errors.first}]},
-
:status => :unprocessable_entity
-
end
-
end
-
-
private
-
-
def create_params
-
params.require(:data).permit :new_phone_number
-
end
-
end
-
end
-
module BxBlockProfile
-
class CoursesController < ApplicationController
-
-
def create
-
@profile = current_user.profiles.find_by(profile_role:"jobseeker")
-
-
if @profile.present?
-
@courses = BxBlockProfile::Course.new(courses_params.merge({profile_id: @profile.id}))
-
if @courses.save
-
render json: BxBlockProfile::CourseSerializer.new(@courses
-
).serializable_hash, status: :created
-
else
-
render json: {
-
errors: format_activerecord_errors(@courses.errors)
-
}, status: :unprocessable_entity
-
end
-
else
-
return render json: {errors: [
-
{profile: 'No jobseeker profile exist for this account'},
-
]}, status: :unprocessable_entity
-
end
-
end
-
-
def index
-
@courses = BxBlockProfile::Course.all
-
if @courses.present?
-
render json: BxBlockProfile::CourseSerializer.new(@courses, meta: {
-
message: "Courses List"
-
}).serializable_hash, status: :ok
-
else
-
render json:{meta: {message: "Record not found."}}
-
end
-
end
-
-
def show
-
course = BxBlockProfile::Course.find_by({id: params[:id]})
-
if course.present?
-
render json: BxBlockProfile::CourseSerializer.new(course, meta: {
-
message: "here is the course with the given id"
-
}).serializable_hash, status: :ok
-
else
-
render json:{meta: {message: "Record not found."}}
-
end
-
end
-
-
def destroy
-
course = BxBlockProfile::Course.find_by({id: params[:id]})
-
if course&.destroy
-
render json:{ meta: { message: "Course Removed"}}
-
else
-
render json:{meta: {message: "Record not found."}}
-
end
-
end
-
private
-
-
def current_user
-
@account = AccountBlock::Account.find_by(id: @token.id)
-
end
-
-
def courses_params
-
params.require(:courses).permit \
-
:course_name,
-
:duration,
-
:year
-
end
-
end
-
end
-
module BxBlockProfile
-
class CurrentStatusController < ApplicationController
-
-
def create
-
@profile = current_user.profiles.find_by(profile_role:"jobseeker")
-
if @profile.present?
-
@current_status = @profile.create_current_status(current_status_params)
-
-
if @current_status.save
-
create_industry && create_employment_type && create_current_annual_salary
-
render json: BxBlockProfile::CurrentStatusSerializer.new(@current_status
-
).serializable_hash, status: :created
-
else
-
render json: {
-
errors: format_activerecord_errors(@current_status.errors)
-
}, status: :unprocessable_entity
-
end
-
else
-
return render json: {errors: [
-
{profile: 'No jobseeker profile exist for this account'},
-
]}, status: :unprocessable_entity
-
end
-
end
-
-
private
-
-
def current_user
-
@account = AccountBlock::Account.find_by(id: @token.id)
-
end
-
-
def current_status_params
-
params.require(:current_status).permit \
-
:most_recent_job_title,
-
:company_name,
-
:notice_period,
-
:end_date
-
end
-
-
def create_industry
-
industry = Industry.where(industry_name: params[:industry_name]).first
-
if industry.present?
-
CurrentStatusIndustry.create(current_status_id: @current_status.id, industry_id: industry.id)
-
else
-
industry = Industry.create(industry_name: params[:industry_name])
-
CurrentStatusIndustry.create(current_status_id: @current_status.id, industry_id: industry.id)
-
end
-
end
-
-
def create_employment_type
-
employment_type = EmploymentType.where(employment_type_name: params[:employment_type_name]).first
-
if employment_type.present?
-
CurrentStatusEmploymentType.create(current_status_id: @current_status.id,
-
employment_type_id: employment_type.id)
-
else
-
employment_type = EmploymentType.create(employment_type_name: params[:employment_type_name])
-
CurrentStatusEmploymentType.create(current_status_id: @current_status.id,
-
employment_type_id: employment_type.id)
-
end
-
end
-
-
def create_current_annual_salary
-
current_annual_salary = CurrentAnnualSalary.where(current_annual_salary: params[:current_annual_salary]).first
-
if current_annual_salary.present?
-
CurrentAnnualSalaryCurrentStatus.create(current_status_id: @current_status.id,
-
current_annual_salary_id: current_annual_salary.id)
-
else
-
current_annual_salary = CurrentAnnualSalary.create(current_annual_salary: params[:current_annual_salary])
-
CurrentAnnualSalaryCurrentStatus.create(current_status_id: @current_status.id,
-
current_annual_salary_id: current_annual_salary.id)
-
end
-
end
-
-
end
-
end
-
module BxBlockProfile
-
class EducationalQualificationsController < ApplicationController
-
-
def index
-
@educational_qualifications = EducationalQualification.all
-
render json: EducationalQualificationSerializer.new(@educational_qualifications, meta: {
-
message: "Successfully Loaded"
-
}).serializable_hash, status: :ok
-
#render json: {educational_qualifications: @educational_qualifications, full_messages: "Successfully Loaded"}
-
end
-
-
def create
-
@profile = current_user.profiles.find_by(profile_role:"jobseeker")
-
-
if @profile.present?
-
@educational_qualification = BxBlockProfile::EducationalQualification.new(
-
educational_qualification_params.merge({ profile_id: @profile.id} ))
-
-
if @educational_qualification.save
-
create_field_study && create_degree
-
render json: BxBlockProfile::EducationalQualificationSerializer.new(@educational_qualification
-
).serializable_hash, status: :created
-
else
-
render json: {
-
errors: format_activerecord_errors(@educational_qualification.errors)
-
}, status: :unprocessable_entity
-
end
-
else
-
return render json: {errors: [
-
{profile: 'No jobseeker profile exist for this account'},
-
]}, status: :unprocessable_entity
-
end
-
end
-
-
def show
-
educational_qualification = BxBlockProfile::EducationalQualification.find_by(id: params[:id])
-
render json: EducationalQualificationSerializer.new(educational_qualification, meta: {
-
message: ""
-
}).serializable_hash, status: :ok
-
end
-
-
def update
-
educational_qualification = BxBlockProfile::EducationalQualification.find_by(id: params[:id])
-
if educational_qualification.present?
-
educational_qualification.update(educational_qualification_params)
-
render json: EducationalQualificationSerializer.new(educational_qualification, meta: {
-
message: "Educational Qualification updated successfully"
-
}).serializable_hash, status: :ok
-
else
-
render json: {
-
errors: format_activerecord_errors(educational_qualification.errors)
-
}, status: :unprocessable_entity
-
end
-
end
-
-
def destroy
-
educational_qualification = BxBlockProfile::EducationalQualification.find_by(id: params[:id])
-
if educational_qualification&.destroy
-
render json:{ meta: { message: "Educational Qualification Removed"}}
-
else
-
render json:{meta: {message: "Record not found."}}
-
end
-
end
-
-
-
private
-
-
def current_user
-
@account = AccountBlock::Account.find_by(id: @token.id)
-
end
-
-
def educational_qualification_params
-
params.require(:educational_qualification).permit \
-
:id,
-
:school_name,
-
:start_date,
-
:end_date,
-
:grades,
-
:description,
-
:make_grades_public
-
end
-
-
def create_field_study
-
field_study = FieldStudy.where(field_of_study: params[:field_of_study]).first
-
if field_study.present?
-
EducationalQualificationFieldStudy.create(educational_qualification_id: @educational_qualification.id,
-
field_study_id: field_study.id)
-
else
-
field_study = FieldStudy.create(field_of_study: params[:field_of_study])
-
EducationalQualificationFieldStudy.create(educational_qualification_id: @educational_qualification.id,
-
field_study_id: field_study.id)
-
end
-
end
-
-
def create_degree
-
degree = Degree.where(degree_name: params[:degree_name]).first
-
if degree.present?
-
DegreeEducationalQualification.create(educational_qualification_id: @educational_qualification.id,
-
degree_id: degree.id)
-
else
-
degree = Degree.create(degree_name: params[:degree_name])
-
DegreeEducationalQualification.create(educational_qualification_id: @educational_qualification.id,
-
degree_id: degree.id)
-
end
-
end
-
-
end
-
end
-
module BxBlockProfile
-
class EmploymentTypesController < ApplicationController
-
skip_before_action :validate_json_web_token
-
def create
-
@emp_type = BxBlockProfile::EmploymentType.create(emp_type_params)
-
if @emp_type.save
-
render json: { data: @emp_type, message: 'New Employment Type Added' }, status: :created
-
else
-
render json: {
-
errors: format_activerecord_errors(@emp_type.errors)
-
}, status: :unprocessable_entity
-
end
-
end
-
-
def index
-
@emp_types = BxBlockProfile::EmploymentType.all
-
render json: { data: @emp_types }, status: :ok
-
end
-
-
def show
-
@emp_type = BxBlockProfile::EmploymentType.find(params[:id])
-
render json: { data: @emp_type }, status: :ok
-
end
-
-
private
-
-
def emp_type_params
-
params.require(:employment_type).permit \
-
:employment_type_name
-
end
-
end
-
end
-
module BxBlockProfile
-
class HobbiesController < ApplicationController
-
-
def create
-
@profile = current_user.profiles.find_by(profile_role:"jobseeker")
-
-
if @profile.present?
-
@hobbies = BxBlockProfile::Hobby.new(hobbies_params.merge({profile_id: @profile.id}))
-
if @hobbies.save
-
render json: BxBlockProfile::HobbySerializer.new(@hobbies
-
).serializable_hash, status: :created
-
else
-
render json: {
-
errors: format_activerecord_errors(@hobbies.errors)
-
}, status: :unprocessable_entity
-
end
-
else
-
return render json: {errors: [
-
{profile: 'No jobseeker profile exist for this account'},
-
]}, status: :unprocessable_entity
-
end
-
end
-
-
def index
-
@hobbies = BxBlockProfile::Hobby.all
-
if @hobbies.present?
-
render json: BxBlockProfile::HobbySerializer.new(@hobbies, meta: {
-
message: "Hobbies List"
-
}).serializable_hash, status: :ok
-
else
-
render json:{meta: {message: "Record not found."}}
-
end
-
end
-
-
def show
-
hobby = BxBlockProfile::Hobby.find_by({id: params[:id]})
-
if hobby.present?
-
render json: BxBlockProfile::HobbySerializer.new(hobby, meta: {
-
message: "here is the hobby with the given id"
-
}).serializable_hash, status: :ok
-
else
-
render json:{meta: {message: "Record not found."}}
-
end
-
end
-
-
def destroy
-
hobby = BxBlockProfile::Hobby.find_by({id: params[:id]})
-
if hobby&.destroy
-
render json:{ meta: { message: "Hobyy Removed"}}
-
else
-
render json:{meta: {message: "Record not found."}}
-
end
-
end
-
private
-
-
def current_user
-
@account = AccountBlock::Account.find_by(id: @token.id)
-
end
-
-
def hobbies_params
-
params.require(:hobbies).permit \
-
:title,
-
:category,
-
:description,
-
:make_public
-
end
-
end
-
end
-
module BxBlockProfile
-
class LanguagesController < ApplicationController
-
-
before_action :validate_json_web_token
-
-
PROFICIENCY = [:mediam, :advance]
-
-
def proficiency
-
render json: {proficiences: BxBlockProfile::LanguagesController::PROFICIENCY }
-
end
-
-
def index
-
@languages = Language.all
-
render json: {languages: @languages, full_messages: "Successfully Loaded"}
-
end
-
-
def create
-
@profile = current_user.profiles.find_by(profile_role:"jobseeker")
-
if @profile.present?
-
-
@language = BxBlockProfile::Language.new(language_params.merge({ profile_id: @profile.id} ))
-
if @language.save
-
render json: BxBlockProfile::LanguageSerializer.new(@language
-
).serializable_hash, status: :created
-
else
-
render json: {
-
errors: format_activerecord_errors(@language.errors)
-
}, status: :unprocessable_entity
-
end
-
else
-
return render json: {errors: [
-
{profile: 'No jobseeker profile exist for this account'},
-
]}, status: :unprocessable_entity
-
end
-
end
-
-
def show
-
language = BxBlockProfile::Language.find_by(id: params[:id])
-
-
if language.present?
-
render json: BxBlockProfile::LanguageSerializer.new(language, meta: {
-
message: ""
-
}).serializable_hash, status: :ok
-
else
-
render json:{meta: {message: "Record not found."}}
-
end
-
end
-
-
def update
-
language = BxBlockProfile::Language.find_by(id: params[:id])
-
if language.present?
-
language.update(language_params)
-
render json: LanguageSerializer.new(language, meta: {
-
message: "Language updated successfully"
-
}).serializable_hash, status: :ok
-
else
-
render json: {
-
errors: format_activerecord_errors(language.errors)
-
}, status: :unprocessable_entity
-
end
-
end
-
-
def destroy
-
language = BxBlockProfile::Language.find_by(id: params[:id])
-
if language&.destroy
-
render json:{ meta: { message: "Language Removed"}}
-
else
-
render json:{meta: {message: "Record not found."}}
-
end
-
end
-
-
-
private
-
-
def encode(id)
-
BuilderJsonWebToken.encode id
-
end
-
-
def current_user
-
@account = AccountBlock::Account.find_by(id: @token.id)
-
end
-
-
def language_params
-
params.require(:language).permit \
-
:id,
-
:language,
-
:proficiency
-
end
-
end
-
end
-
module BxBlockProfile
-
class PasswordsController < ApplicationController
-
def update
-
status, result = ChangePasswordCommand.execute \
-
@token.id,
-
update_params[:current_password],
-
update_params[:new_password]
-
-
if status == :created
-
serializer = AccountBlock::AccountSerializer.new(result)
-
render :json => serializer.serializable_hash,
-
:status => :created
-
else
-
render :json => {:errors => [{:profile => result.first}]},
-
:status => status
-
end
-
end
-
-
private
-
-
def update_params
-
params.require(:data)
-
.permit \
-
:current_password,
-
:new_password
-
end
-
end
-
end
-
module BxBlockProfile
-
class ProfilesController < ApplicationController
-
-
def create
-
# @profile = current_user.create_profile(profile_params)
-
@profile = BxBlockProfile::Profile.create(profile_params.merge({account_id: current_user.id}))
-
-
if @profile.save
-
render json: BxBlockProfile::ProfileSerializer.new(@profile
-
).serializable_hash, status: :created
-
else
-
render json: {
-
errors: format_activerecord_errors(@profile.errors)
-
}, status: :unprocessable_entity
-
end
-
end
-
-
def show
-
profile = BxBlockProfile::Profile.find(params[:id])
-
if profile.present?
-
render json: ProfileSerializer.new(profile).serializable_hash,status: :ok
-
else
-
render json: {
-
errors: format_activerecord_errors(profile.errors)
-
}, status: :unprocessable_entity
-
end
-
end
-
-
def update
-
status, result = UpdateAccountCommand.execute(@token.id, update_params)
-
-
if status == :ok
-
serializer = AccountBlock::AccountSerializer.new(result)
-
render :json => serializer.serializable_hash,
-
:status => :ok
-
else
-
render :json => {:errors => [{:profile => result.first}]},
-
:status => status
-
end
-
end
-
-
-
def destroy
-
profile = BxBlockProfile::Profile.find(params[:id])
-
if profile.present?
-
profile.destroy
-
render json:{ meta: { message: "Profile Removed"}}
-
else
-
render json:{meta: {message: "Record not found."}}
-
end
-
end
-
-
def update_profile
-
profile = BxBlockProfile::Profile.find_by(id: params[:id])
-
profile.update(profile_params)
-
if profile&.photo&.attached?
-
render json: ProfileSerializer.new(profile, meta: {
-
message: "Profile Updated Successfully"
-
}).serializable_hash, status: :ok
-
else
-
render json: {
-
errors: format_activerecord_errors(profile.errors)
-
}, status: :unprocessable_entity
-
end
-
end
-
-
def user_profiles
-
profiles = current_user.profiles
-
render json: ProfileSerializer.new(profiles, meta: {
-
message: "Successfully Loaded"
-
}).serializable_hash, status: :ok
-
end
-
-
private
-
-
def current_user
-
@account = AccountBlock::Account.find_by(id: @token.id)
-
end
-
-
def profile_params
-
params.require(:profile).permit(:id, :country, :address, :city, :postal_code, :photo, :profile_role)
-
end
-
-
def update_params
-
params.require(:data).permit \
-
:first_name,
-
:last_name,
-
:current_password,
-
:new_password,
-
:new_email,
-
:new_phone_number
-
end
-
end
-
end
-
module BxBlockProfile
-
class ProjectsController < ApplicationController
-
-
def index
-
@projects = Project.all
-
render json: ProjectSerializer.new(@projects, meta: {
-
message: "Successfully Loaded"
-
}).serializable_hash, status: :ok
-
end
-
-
def create
-
@profile = current_user.profiles.find_by(profile_role:"jobseeker")
-
if @profile.present?
-
@project = BxBlockProfile::Project.new(project_params.merge({ profile_id: @profile.id} ))
-
if @project.save
-
create_associated_with
-
render json: BxBlockProfile::ProjectSerializer.new(@project
-
).serializable_hash, status: :created
-
else
-
render json: {
-
errors: format_activerecord_errors(@project.errors)
-
}, status: :unprocessable_entity
-
end
-
else
-
render json: {
-
errors: format_activerecord_errors(@profile.errors)
-
}, status: :unprocessable_entity
-
end
-
end
-
-
def show
-
project = BxBlockProfile::Project.find_by(id: params[:id])
-
if project.present?
-
render json: BxBlockProfile::ProjectSerializer.new(project, meta: {
-
message: ""
-
}).serializable_hash, status: :ok
-
else
-
render json:{meta: {message: "Record not found."}}
-
end
-
end
-
-
def update
-
project = BxBlockProfile::Project.find_by(id: params[:id])
-
if project.present?
-
project.update(project_params)
-
render json: ProjectSerializer.new(project, meta: {
-
message: "Project updated successfully"
-
}).serializable_hash, status: :ok
-
else
-
render json: {
-
errors: format_activerecord_errors(project.errors)
-
}, status: :unprocessable_entity
-
end
-
end
-
-
def destroy
-
project = BxBlockProfile::Project.find_by(id: params[:id])
-
if project&.destroy
-
render json:{ meta: { message: "Project Removed"}}
-
else
-
render json:{meta: {message: "Record not found."}}
-
end
-
end
-
-
private
-
-
def current_user
-
@account = AccountBlock::Account.find_by(id: @token.id)
-
end
-
-
def project_params
-
params.require(:project).permit \
-
:id,
-
:project_name,
-
:start_date,
-
:end_date,
-
:add_members,
-
:url,
-
:description,
-
:make_projects_public
-
end
-
-
def create_associated_with
-
associated = Associated.where(associated_with_name: params[:associated_with_name]).first
-
if associated.present?
-
AssociatedProject.create(project_id: @project.id, associated_id: associated.id)
-
else
-
associated = Associated.create(associated_with_name: params[:associated_with_name])
-
AssociatedProject.create(project_id: @project.id, associated_id: associated.id)
-
end
-
end
-
-
end
-
end
-
module BxBlockProfile
-
class PublicationPatentsController < ApplicationController
-
-
def create
-
@profile = current_user.profiles.find_by(profile_role:"jobseeker")
-
if @profile.present?
-
@publication_patent = @profile.create_publication_patent(publication_patent_params)
-
if @publication_patent.save
-
render json: BxBlockProfile::PublicationPatentSerializer.new(@publication_patent
-
).serializable_hash, status: :created
-
else
-
return render json: {errors: [
-
{profile: 'No jobseeker profile exist for this account'},
-
]}, status: :unprocessable_entity
-
end
-
end
-
end
-
-
def index
-
@pp = BxBlockProfile::PublicationPatent.all
-
if @pp.present?
-
render json: BxBlockProfile::PublicationPatentSerializer.new(@pp, meta: {
-
message: "List Of Publication"
-
}).serializable_hash, status: :ok
-
else
-
render json:{meta: {message: "Record not found."}}
-
end
-
end
-
-
def show
-
pp = BxBlockProfile::PublicationPatent.find(params[:id])
-
if pp.present?
-
render json: BxBlockProfile::PublicationPatentSerializer.new(pp, meta: {
-
message: "Here are the publication details"
-
}).serializable_hash, status: :ok
-
else
-
render json:{meta: {message: "Record not found."}}
-
end
-
end
-
-
def destroy
-
pp = BxBlockProfile::PublicationPatent.find_by(id: params[:id])
-
if pp&.destroy
-
render json:{ meta: { message: "Publication Removed"}}
-
else
-
render json:{meta: {message: "Record not found."}}
-
end
-
end
-
-
private
-
-
def current_user
-
@account = AccountBlock::Account.find_by(id: @token.id)
-
end
-
-
def publication_patent_params
-
params.require(:publication_patent).permit \
-
:title,
-
:publication,
-
:authors,
-
:url,
-
:description,
-
:make_public
-
end
-
end
-
end
-
module BxBlockProfile
-
class TestScoreAndCoursesController < ApplicationController
-
-
def create
-
@profile = current_user.profiles.find_by(profile_role:"jobseeker")
-
-
if @profile.present?
-
@test_score = BxBlockProfile::TestScoreAndCourse.new(test_score_params.merge({profile_id: @profile.id}))
-
if @test_score.save
-
render json: BxBlockProfile::TestScoreAndCourseSerializer.new(@test_score
-
).serializable_hash, status: :created
-
else
-
render json: {
-
errors: format_activerecord_errors(@test_score.errors)
-
}, status: :unprocessable_entity
-
end
-
else
-
return render json: {errors: [
-
{profile: 'No jobseeker profile exist for this account'},
-
]}, status: :unprocessable_entity
-
end
-
end
-
-
def index
-
@tc = BxBlockProfile::TestScoreAndCourse.all
-
if @tc.present?
-
render json: BxBlockProfile::TestScoreAndCourseSerializer.new(@tc, meta: {
-
message: "List Of Test Score And Courses"
-
}).serializable_hash, status: :ok
-
else
-
render json:{meta: {message: "Record not found."}}
-
end
-
end
-
-
def show
-
test_score = BxBlockProfile::TestScoreAndCourse.find_by({id: params[:id]})
-
-
if test_score.present?
-
render json: BxBlockProfile::TestScoreAndCourseSerializer.new(test_score, meta: {
-
message: "here is the test score for the given id"
-
}).serializable_hash, status: :ok
-
else
-
render json:{meta: {message: "Record not found."}}
-
end
-
end
-
-
def destroy
-
test_score = BxBlockProfile::TestScoreAndCourse.find_by({id: params[:id]})
-
if test_score&.destroy
-
render json:{ meta: { message: "Test Score Removed"}}
-
else
-
render json:{meta: {message: "Record not found."}}
-
end
-
end
-
-
private
-
-
def current_user
-
@account = AccountBlock::Account.find_by(id: @token.id)
-
end
-
-
def test_score_params
-
params.require(:test_score).permit \
-
:title,
-
:associated_with,
-
:score,
-
:test_date,
-
:description,
-
:make_public
-
end
-
end
-
end
-
module BxBlockProfile
-
class ValidationsController < ApplicationController
-
skip_before_action :validate_json_web_token, :only => [:index]
-
-
def index
-
render :json => {
-
:data => [{
-
:email_validation_regexp => email_regex,
-
:password_validation_regexp => password_regex,
-
:password_validation_rules => password_rules,
-
}],
-
}
-
end
-
-
private
-
-
def email_regex
-
AccountBlock::EmailValidation.regex_string
-
end
-
-
def password_regex
-
AccountBlock::PasswordValidation.regex_string
-
end
-
-
def password_rules
-
AccountBlock::PasswordValidation.rules
-
end
-
end
-
end
-
module BxBlockProjecttemplates
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
module BxBlockPushNotifications
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
-
def current_user
-
@current_user ||= AccountBlock::Account.find(@token.id) if @token.present?
-
end
-
-
end
-
end
-
module BxBlockPushNotifications
-
class PushNotificationsController < ApplicationController
-
-
def index
-
push_notifications = current_user.push_notifications
-
if push_notifications.present?
-
serializer = BxBlockPushNotifications::PushNotificationSerializer.new(
-
push_notifications
-
)
-
render json: serializer.serializable_hash, status: :ok
-
else
-
render json: {
-
errors: 'There is no push notification.'
-
}, status: :not_found
-
end
-
end
-
-
def create
-
push_notification = BxBlockPushNotifications::PushNotification.new(
-
push_notifications_params.merge({account_id: current_user.id})
-
)
-
if push_notification.save
-
serializer = BxBlockPushNotifications::PushNotificationSerializer.new(push_notification)
-
render json: serializer.serializable_hash, status: :ok
-
else
-
render json: {
-
errors: [{
-
push_notification: push_notification.errors.full_messages
-
}]
-
}, status: :unprocessable_entity
-
end
-
rescue Exception => push_notification
-
render json: {errors: [{push_notification: push_notification.message}]},
-
status: :unprocessable_entity
-
end
-
-
def update
-
push_notification = BxBlockPushNotifications::PushNotification.find_by(
-
id: params[:id], push_notificable_id: current_user.id
-
)
-
return render json: { message: "Not Found" },
-
status: :not_found if push_notification.blank?
-
-
if push_notification.update(push_notifications_params)
-
serializer = BxBlockPushNotifications::PushNotificationSerializer.new(push_notification)
-
render json: serializer.serializable_hash,
-
status: :ok
-
else
-
render json: { errors: [{push_notification: push_notification.errors.full_messages}]},
-
status: :unprocessable_entity
-
end
-
rescue Exception => push_notification
-
render json: {errors: [{push_notification: push_notification.message}]},
-
status: :unprocessable_entity
-
end
-
-
def show
-
push_notification = current_user.push_notifications.find(params[:id])
-
-
if push_notification.blank?
-
render json: { message: "Push Notification Not Found" },
-
status: :not_found
-
else
-
render json: BxBlockPushNotifications::PushNotificationSerializer.new(push_notification)
-
end
-
end
-
-
private
-
-
def push_notifications_params
-
params.require(:data)[:attributes].permit(
-
:push_notificable_id,
-
:push_notificable_type,
-
:remarks, :is_read
-
)
-
end
-
end
-
end
-
module BxBlockReferrals
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
1
module BxBlockReferrals
-
1
class ReferralsController < BuilderBase::ApplicationController
-
1
include BuilderJsonWebToken::JsonWebTokenValidation
-
1
include JSONAPI::Deserialization
-
1
before_action :validate_json_web_token
-
-
1
def get_user_referral
-
2
@account = AccountBlock::Account.find_by(id: @token.id)
-
2
if @account.present?
-
2
if @account.referral_user.present?
-
1
render json: BxBlockReferrals::ReferralSerializer.new(@account.referral_user).serializable_hash, status: :ok
-
else
-
1
return render json: { message: "Account referral not created" }, status: 422
-
end
-
else
-
return render json: { message: "Account not found" }, status: 422
-
end
-
end
-
-
1
def add_referral
-
2
@account = AccountBlock::Account.find_by(id: @token.id)
-
2
@referral = ReferralUser.find_by(referral_code: params[:referral_code])
-
2
if @referral.present?
-
1
if @account.referral_user.referral_by.nil?
-
1
unless @account.referral_user.referral_code == params[:referral_code]
-
1
@account.referral_user.update(referral_by: params[:referral_code])
-
1
render json: BxBlockReferrals::ReferralSerializer.new(@account.referral_user).serializable_hash, status: :ok
-
else
-
return render json: { message: "You can't used this code" }, status: 422
-
end
-
else
-
return render json: { message: "used already" }, status: 422
-
end
-
else
-
1
return render json: { message: "referral code not authorized" }, status: 422
-
end
-
end
-
-
1
def create_referral
-
2
@account = AccountBlock::Account.find_by(id: @token.id)
-
2
if @account.present?
-
2
if @account.referral_user.nil?
-
1
referral_code = attach_shareable_link_to_account
-
1
refferal_user = BxBlockReferrals::ReferralUser.create(account_id: @account.id, referral_code: referral_code)
-
else
-
1
return render json: { message: "already create referral code" }, status: 422
-
end
-
1
if refferal_user.save
-
# render json: BxBlockReferrals::ReferralSerializer.new(refferal_user).serializable_hash, status: :ok
-
1
render json: {referral_code: refferal_user.referral_code}, status: :ok
-
else
-
return render json: { message: "something wrong" }, status: 422
-
end
-
end
-
end
-
-
1
private
-
-
1
def attach_shareable_link_to_account
-
1
o = [('a'..'z'), ('A'..'Z'), ('1'..'9')].map(&:to_a).flatten
-
11
@refer_code = (0...10).map { o[rand(o.length)] }.join
-
1
return @refer_code
-
end
-
end
-
end
-
module BxBlockRefundmanagement
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
module BxBlockRequestManagement
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
module BxBlockRequestManagement
-
class RequestsController < ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
before_action :validate_json_web_token
-
-
before_action :load_account
-
-
def index
-
requests = BxBlockRequestManagement::Request.where(
-
"(sender_id = ? or account_id = ?)",
-
@current_account.id, @current_account.id
-
)
-
requests = requests.public_send(params[:filter_by_request]) if params[:filter_by_request]
-
-
if params[:filter_by].present?
-
if params[:filter_by] == 'newest_first'
-
requests = requests.order('requests.created_at desc')
-
elsif params[:filter_by] == 'oldest_first'
-
requests = requests.order('requests.created_at asc')
-
end
-
end
-
-
if params[:search_by_name].present?
-
requests = requests.joins(:sender).where(
-
"accounts.first_name ILIKE ? or accounts.last_name ILIKE ?",
-
"%#{params[:search_by_name]}%", "%#{params[:search_by_name]}%"
-
).distinct
-
end
-
BxBlockRequestManagement::Request.mutual_friend(@current_account, requests)
-
-
if requests.present?
-
json_data = BxBlockRequestManagement::RequestSerializer.new(
-
requests, params: {current_user: @current_account}
-
).serializable_hash
-
json_data[:total_requests_count] = json_data[:data].count rescue 0
-
render json: json_data
-
else
-
render json: [],
-
status: :not_found
-
end
-
end
-
-
def create
-
return if @current_account.nil?
-
begin
-
request = BxBlockRequestManagement::Request.find_or_initialize_by(
-
request_params.merge(sender_id: @current_account.id)
-
)
-
if request.save
-
render json: {
-
**BxBlockRequestManagement::RequestSerializer.new(
-
request, params: {current_user: @current_account}
-
).serializable_hash,
-
message: 'Request successfully send'
-
}
-
else
-
render json: {errors: format_activerecord_errors(request.errors)},
-
status: :unprocessable_entity
-
end
-
rescue Exception => request
-
render json: {errors: request.message},
-
status: :unprocessable_entity
-
end
-
end
-
-
def show
-
request = BxBlockRequestManagement::Request.where(
-
"(sender_id = ? or account_id = ?)", @current_account.id, @current_account.id
-
).find_by(id: params[:id])
-
-
return render json: {errors: [
-
{Request: 'Not found'},
-
]}, status: :not_found if request.blank?
-
-
render json: BxBlockRequestManagement::RequestSerializer.new(
-
request, params: {current_user: @current_account}
-
).serializable_hash
-
end
-
-
def update
-
return if @current_account.nil?
-
begin
-
request = BxBlockRequestManagement::Request.where(
-
"(sender_id = ? or account_id = ?)", @current_account.id, @current_account.id
-
).find_by(id: params[:id])
-
-
return render json: {errors: [
-
{Request: 'Not found'},
-
]}, status: :not_found if request.blank?
-
-
if request.update(request_params)
-
render json: {
-
**BxBlockRequestManagement::RequestSerializer.new(
-
request, params: {current_user: @current_account}
-
).serializable_hash,
-
message: 'Request successfully updated'
-
}
-
else
-
render json: {errors: format_activerecord_errors(request.errors)},
-
status: :unprocessable_entity
-
end
-
rescue Exception => request
-
render json: {errors: request.message},
-
status: :unprocessable_entity
-
end
-
end
-
-
private
-
-
def request_params
-
params.require(:data).permit \
-
:status, :account_id
-
end
-
-
def format_activerecord_errors(errors)
-
result = []
-
errors.each do |attribute, error|
-
result << { attribute => error }
-
end
-
result
-
end
-
-
def load_account
-
@current_account = AccountBlock::Account.find_by(id: @token.id)
-
-
if @current_account.nil?
-
render json: {
-
message: "Account with id #{@token.id} doesn't exist"
-
}, status: :not_found
-
end
-
end
-
end
-
end
-
module BxBlockReviews
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
def current_user
-
begin
-
@current_user = AccountBlock::Account.find(@token.id)
-
rescue ActiveRecord::RecordNotFound => e
-
return render json: {errors: [
-
{message: 'Please login again.'},
-
]}, status: :unprocessable_entity
-
end
-
end
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
module BxBlockReviews
-
class ReviewsController < ApplicationController
-
before_action :load_account, only: [:index]
-
before_action :load_review, only: [:update]
-
-
def index
-
reviews = BxBlockReviews::Review.find_by_account_id(@account.id)#@account.reviews
-
render json: ReviewSerializer.new(reviews).serializable_hash,
-
status: :ok
-
end
-
-
def create
-
review_attributes = jsonapi_deserialize(params)
-
service = BxBlockReviews::Create.new(current_user, review_attributes)
-
result = service.execute
-
if result.persisted?
-
render json: ReviewSerializer.new(result).serializable_hash,
-
status: :ok
-
else
-
render json: ErrorSerializer.new(result).serializable_hash,
-
status: :unprocessable_entity
-
end
-
end
-
-
def update
-
return if @review.nil?
-
-
review_attributes = jsonapi_deserialize(params)
-
service = BxBlockReviews::Update.new(@review, review_attributes)
-
result = service.execute
-
if result.persisted?
-
render json: ReviewSerializer.new(result).serializable_hash,
-
status: :ok
-
else
-
render json: ErrorSerializer.new(result).serializable_hash,
-
status: :unprocessable_entity
-
end
-
end
-
-
private
-
-
def load_account
-
@account = AccountBlock::Account.find(params[:account_id])
-
if @account.nil?
-
render json: { message: 'Account does not exist' },
-
status: :not_found
-
end
-
end
-
-
def load_review
-
@review = Review.find(params[:id])
-
if @review.nil?
-
render json: { message: 'Review does not exist' },
-
status: :not_found
-
end
-
end
-
-
end
-
end
-
module BxBlockRolesPermissions
-
class ApplicationController < BuilderBase::ApplicationController
-
# protect_from_forgery with: :exception
-
end
-
end
-
module BxBlockScreenshoteditor0
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
module BxBlockSettings
-
class ApplicationController < BuilderBase::ApplicationController
-
# protect_from_forgery with: :exception
-
end
-
end
-
module BxBlockSettings
-
class SettingsController < ApplicationController
-
def index
-
settings = Setting.all
-
render json: { settings: settings, message: 'Successfully loaded' }
-
end
-
end
-
end
-
module BxBlockShoppingCart
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
module BxBlockShoppingCart
-
class AvailabilitiesController < ApplicationController
-
before_action :get_service_provider, only: %i(get_booked_time_slots)
-
-
def get_booked_time_slots
-
unless params[:service_provider_id].blank? || params[:booking_date].blank?
-
render json: BxBlockShoppingCart::OrderSerializer.new(
-
BxBlockShoppingCart::Order.where(
-
service_provider_id: params[:service_provider_id],
-
booking_date: params[:booking_date].to_datetime
-
), meta: {
-
availability: BxBlockAppointmentManagement::Availability.find_by(
-
service_provider_id: @service_provider.id
-
)
-
}
-
).serializable_hash
-
else
-
render json: {errors: [
-
{availability: 'Date or Service provider Account id is empty'},
-
]}, status: :unprocessable_entity
-
end
-
end
-
-
private
-
-
def get_service_provider
-
render json: {
-
errors: 'Please enter service_provider'
-
} and return unless params[:service_provider_id].present?
-
@service_provider = AccountBlock::Account.find(params[:service_provider_id])
-
end
-
end
-
end
-
module BxBlockShoppingCart
-
class CustomerAppointmentsController < ApplicationController
-
def customer_orders
-
if params[:filter_by].present? && params[:filter_by].downcase == 'history'
-
orders = BxBlockShoppingCart::Order.where(
-
customer_id: @token.id, status: ['completed', 'cancelled']
-
)
-
else
-
orders = BxBlockShoppingCart::Order.where(
-
customer_id: @token.id, status: params[:filter_by]
-
) if params[:filter_by].present?
-
end
-
render json: {message: 'No order present'} and return unless orders.present?
-
render json: BxBlockShoppingCart::OrderSerializer.new(
-
orders, meta: {message: "List for #{params[:filter_by]}"}
-
).serializable_hash
-
end
-
-
def update_notification_setting
-
@order = BxBlockShoppingCart::Order.find(params[:id])
-
@order.update(order_notification_params)
-
render json: {
-
message: "Update notify me #{params[:notify_me]}"
-
} and return @order.update(order_notification_params)
-
render json: { errors: format_activerecord_errors(order.errors) }
-
end
-
-
private
-
-
def order_notification_params
-
fields = params.permit(:notify_me)
-
fields.merge(:job_status => true) if !@order.job_status and params[:notify_me]
-
fields
-
end
-
-
def format_activerecord_errors(errors)
-
result = []
-
errors.each do |attribute, error|
-
result << { attribute => error }
-
end
-
result
-
end
-
end
-
end
-
module BxBlockShoppingCart
-
class OrdersController < ApplicationController
-
before_action :get_user, only: %i(create)
-
before_action :order_params, only: [:create]
-
before_action :get_service_provider, only: %i(get_booked_time_slots)
-
-
def create
-
@order = BxBlockShoppingCart::Order.new(order_params)
-
if @order.save
-
render json: BxBlockShoppingCart::OrderSerializer.new(@order, meta: {
-
message: 'Order Created Successfully',
-
}).serializable_hash, status: :created
-
else
-
render json: {errors: format_activerecord_errors(@order.errors)},
-
status: :unprocessable_entity
-
end
-
end
-
-
def show
-
order = BxBlockShoppingCart::Order.find(params[:id])
-
render json: {errors: 'Order dose not present'} and return unless order.present?
-
render json: BxBlockShoppingCart::OrderSerializer.new(order)
-
end
-
-
#========================================================================
-
# Route is not created for this action
-
#========================================================================
-
-
def get_booked_time_slots
-
unless params[:service_provider_id].blank? || params[:booking_date].blank?
-
render json: BxBlockShoppingCart::OrderSerializer.new(
-
BxBlockShoppingCart::Order.where(
-
service_provider_id: params[:service_provider_id],
-
booking_date: params[:booking_date].to_datetime
-
),
-
meta: {
-
availability: @service_provider.availabilities
-
}
-
).serializable_hash
-
else
-
render json: {errors: [
-
{availability: 'Date or Service provider Account id is empty'},
-
]}, status: :unprocessable_entity
-
end
-
end
-
-
private
-
def order_params
-
params.require(:order).permit(:service_provider_id, :address_id, :booking_date,
-
:slot_start_time, :order_type, :total_fees, :instructions,
-
:service_total_time_minutes, :coupon_id, :is_coupon_applied,
-
:discount, sub_category_ids: []
-
).merge(status: 'scheduled', customer_id: @customer.id)
-
end
-
-
def format_activerecord_errors(errors)
-
result = []
-
errors.each do |attribute, error|
-
result << { attribute => error }
-
end
-
result
-
end
-
-
def get_user
-
@customer = AccountBlock::Account.find(@token.id)
-
render json: {errors: 'Customer is invalid'} and return unless @customer.present?
-
end
-
-
def get_service_provider
-
unless params[:service_provider_id].present?
-
render json: {errors: 'Please enter service_provider'} and return
-
end
-
@service_provider = AccountBlock::Account.find(params[:service_provider_id])
-
end
-
end
-
end
-
module BxBlockShoppingCart
-
class ServiceProviderAppointmentsController < ApplicationController
-
def filter_order
-
if params[:filter_by].present? && params[:filter_by].downcase == 'history'
-
orders = BxBlockShoppingCart::Order.where(
-
service_provider_id: @token.id, status: ['completed', 'cancelled']
-
)
-
else
-
orders = BxBlockShoppingCart::Order.where(
-
service_provider_id: @token.id, status: params[:filter_by]
-
) if params[:filter_by].present?
-
end
-
render json: {message: 'No order present'} and return unless orders.present?
-
render json: BxBlockShoppingCart::OrderSerializer.new(
-
orders, meta: {message: "List for #{params[:filter_by]}"}
-
).serializable_hash
-
end
-
-
def start_order
-
order = ::BxBlockShoppingCart::Order.find(params[:id])
-
render json: {errors: 'Order dose not present'} and return unless order.present?
-
render json: {message: 'Order is already started'} and return if order.status == 'on_going'
-
render json: ::BxBlockShoppingCart::OrderSerializer.new(
-
order, meta: {message: 'Order is started'}
-
) and return if order.update(status: 'on_going', ongoing_time: Time.now.strftime('%I:%M %p'))
-
render json: {errors: format_activerecord_errors(order.errors)},
-
status: :unprocessable_entity
-
end
-
-
def finish_order
-
order = ::BxBlockShoppingCart::Order.find(params[:id])
-
render json: {errors: 'Order dose not present'} and return unless order.present?
-
render json: {
-
message: 'Please start your order first'
-
} and return if order.status != 'on_going' and order.status != 'completed'
-
render json: {
-
message: 'Your order is already finished'
-
} and return if order.status == 'completed'
-
render json: ::BxBlockShoppingCart::OrderSerializer.new(
-
order, meta: {message: 'Order is finished'}
-
) and return if order.update(status: 'completed', finish_at: Time.now.strftime('%I:%M %p'))
-
render json: {errors: format_activerecord_errors(order.errors)},
-
status: :unprocessable_entity
-
end
-
-
def get_sp_details
-
unless params[:service_provider_id].blank? || params[:availability_date].blank?
-
render json: ::BxBlockCalendar::AvailabilitySerializer.new(
-
BxBlockAppointmentManagement::Availability.sp_details(
-
params[:service_provider_id],
-
params[:availability_date]
-
)
-
)
-
else
-
render json: {errors: [
-
{availability: 'Date or Service provider Account id is empty'},
-
]}, status: :unprocessable_entity
-
end
-
end
-
-
private
-
-
def format_activerecord_errors(errors)
-
result = []
-
errors.each do |attribute, error|
-
result << { attribute => error }
-
end
-
result
-
end
-
end
-
end
-
module BxBlockStatisticsreports
-
class ApplicationController < BuilderBase::ApplicationController
-
include BuilderJsonWebToken::JsonWebTokenValidation
-
-
before_action :validate_json_web_token
-
-
rescue_from ActiveRecord::RecordNotFound, :with => :not_found
-
-
private
-
-
def not_found
-
render :json => {'errors' => ['Record not found']}, :status => :not_found
-
end
-
end
-
end
-
1
module BxBlockStories
-
1
class BlogsController < ApplicationController
-
-
1
def active_blogs
-
1
active_blogs = BxBlockStories::Blog.where(status: "active")
-
1
if active_blogs.present?
-
render json: BxBlockStories::BlogsSerializer.new(active_blogs).serializable_hash
-
else
-
1
render json: {data: []}, status: :ok
-
end
-
end
-
-
1
def show
-
2
@blog = BxBlockStories::Blog.find_by(url: params[:url])
-
2
if @blog.present?
-
render json: BxBlockStories::BlogsSerializer.new(@blog).serializable_hash
-
else
-
2
return render json: {errors: [{message: 'Blog not found'}]}, status: :ok
-
end
-
end
-
end
-
end
-
1
module BxBlockStories
-
1
class StoriesController < ApplicationController
-
1
include BuilderJsonWebToken::JsonWebTokenValidation
-
# before_action :validate_json_web_token
-
-
1
def active_stories
-
1
active_stories = BxBlockStories::Story.where(active: true)
-
1
if active_stories.present?
-
1
render json: BxBlockStories::StorySerializer.new(active_stories).serializable_hash
-
else
-
render json: {data: []}, status: :ok
-
end
-
end
-
-
1
def destroy
-
2
story = BxBlockStories::Story.find_by(id: params[:id])
-
2
return if story.nil?
-
1
if story.destroy
-
1
render json: { message: 'Story deleted successfully' }, status: :ok
-
else
-
render json: ErrorSerializer.new(story).serializable_hash,
-
status: :unprocessable_entity
-
end
-
end
-
end
-
end
-
class WebhookController < ApplicationController
-
before_action :fetch_order, only: [:receive, :send_order_update_info_to_user]
-
-
def receive
-
return render json: { message: "order not found" } if @order.nil?
-
@order.ship_rocket_awb_code = params["awb"]
-
@order.ship_rocket_status = params["current_status"].downcase
-
@order.ship_rocket_order_id = params["order_id"]
-
@order.status = params["shipment_status"].downcase
-
@order.ship_rocket_shipment_id = params["shipment_status_id"]
-
@order.updated_at = params["current_timestamp"]
-
@order.ship_rocket_status_code = params["current_status_id"]
-
@order.updated_at = Time.now
-
@order.save
-
-
send_order_update_info_to_user
-
end
-
-
def send_order_update_info_to_user
-
SystemMailer.send_order_update_info(@order).deliver!
-
end
-
-
private
-
-
def fetch_order
-
@order = BxBlockOrderManagement::Order.find_by(ship_rocket_order_id: params[:order_id])
-
end
-
end
-
module AccountBlock
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
class ApplicationJob < ActiveJob::Base
-
# Automatically retry jobs that encountered a deadlock
-
# retry_on ActiveRecord::Deadlocked
-
-
# Most jobs are safe to ignore if the underlying records are no longer available
-
# discard_on ActiveJob::DeserializationError
-
end
-
module BuilderBase
-
class ApplicationJob < ::ApplicationJob
-
end
-
end
-
module BxBlockActivitylog
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockAddress
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockAdmin
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockAnalytics3
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockAppointmentManagement
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockAttachment
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockBook
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
class BxBlockBook::DeleteUnusedBooksJob < ApplicationJob
-
queue_as :default
-
-
def perform
-
Rails.logger.info '=======================Job started================'
-
books = BxBlockBook::Book.where(book_status: 'pending')#.where(created_at: (Time.now-1.day))
-
books.each do |book|
-
Rails.logger.info "=======================#{book.id}================"
-
order = BxBlockOrderManagement::Order.find_by(book_id: book.id)
-
book.destroy! if order.nil?
-
Rails.logger.info "=======================Failed: #{book.errors.inspect}================"
-
end
-
Rails.logger.info '=======================Job completed================'
-
end
-
end
-
module BxBlockBulkUploading
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockCalendar
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockCatalogue
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockCategories
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockCfanimationsandtransition2
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockCfgooglephotosintegration2
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockCfinterfaceforbookpreview2
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockCfshiprocketintegration2
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockContentManagement
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockCors
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockCouponCg
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockCoupons
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockCustomForm
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockCustomUserSubs
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockDashboard
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockDiscountsoffers
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
class BxBlockDiscountsoffers::DeactiveExpiredOffersJob < ApplicationJob
-
queue_as :default
-
-
def perform
-
Rails.logger.info '=======================Job started================'
-
offers = BxBlockDiscountsoffers::Offer.where(active: true)
-
offers.each do |offer|
-
Rails.logger.info "=======================#{offer.id}================"
-
if Time.zone.now.to_date > offer&.valid_to&.to_date
-
offer.update_column(:active, false)
-
end
-
Rails.logger.info "=======================Failed: #{offer.errors.inspect}================"
-
end
-
Rails.logger.info '=======================Job completed================'
-
end
-
end
-
module BxBlockDownload
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockDragdropinterface
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockEmailNotifications
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockFavourites
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockFedexIntegration
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockForgotPassword
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockGallery
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockHelpCentre
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockInvoicebilling
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockLandingpage3
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockLike
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockLocation
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockLogin
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockNotifications
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockOrderManagement
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockOrdersummary
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockPaymentAdmin
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockPlan
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockPosts
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockProfile
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockProjecttemplates
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockPushNotifications
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockReferrals
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockRefundmanagement
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockRequestManagement
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockReviews
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockRolesPermissions
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockScreenshoteditor0
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockSettings
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockShoppingCart
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
module BxBlockStatisticsreports
-
class ApplicationJob < BuilderBase::ApplicationJob
-
end
-
end
-
class BxBlockStories::DeactivePastStoriesJob < ApplicationJob
-
queue_as :default
-
-
def perform
-
Rails.logger.info '=======================Job started================'
-
stories = BxBlockStories::Story.all
-
stories.each do |story|
-
Rails.logger.info "=======================#{story.id}================"
-
if Time.zone.now > story&.valid_till
-
story.update_column(:active, false)
-
end
-
Rails.logger.info "=======================Failed: #{story.errors.inspect}================"
-
end
-
Rails.logger.info '=======================Job completed================'
-
end
-
end
-
module AccountBlock
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module AccountBlock
-
class EmailValidationMailer < ApplicationMailer
-
def activation_email
-
@account = params[:account]
-
@host = Rails.env.development? ? 'http://localhost:3000' : params[:host]
-
-
token = encoded_token
-
-
@url = "#{@host}/account/accounts/email_confirmation?token=#{token}"
-
-
attachments.inline['logo.jpg'] = File.read("#{Rails.root}/app/assets/images/logo.jpg")
-
attachments.inline['image-1.png'] = File.read("#{Rails.root}/app/assets/images/image-1.png")
-
attachments.inline['image-2.png'] = File.read("#{Rails.root}/app/assets/images/image-2.png")
-
attachments.inline['image-3.png'] = File.read("#{Rails.root}/app/assets/images/image-3.png")
-
attachments.inline['image-4.png'] = File.read("#{Rails.root}/app/assets/images/image-4.png")
-
attachments.inline['image-5.png'] = File.read("#{Rails.root}/app/assets/images/image-5.png")
-
attachments.inline['image-6.png'] = File.read("#{Rails.root}/app/assets/images/image-6.png")
-
-
mail(
-
to: @account.email,
-
from: "Whitebook <#{ENV['SMTP_USERNAME']}>",
-
subject: 'Account activation') do |format|
-
format.html { render 'activation_email' }
-
end
-
end
-
-
private
-
-
def encoded_token
-
BuilderJsonWebToken.encode @account.id, 10.minutes.from_now
-
end
-
end
-
end
-
1
module AccountBlock
-
1
class WelcomeMailer < ApplicationMailer
-
1
def welcome_email
-
1
@account = params[:account]
-
# attachments.inline['logo.jpg'] = File.read("#{Rails.root}/app/assets/images/logo.jpg")
-
# attachments.inline['image-1.png'] = File.read("#{Rails.root}/app/assets/images/image-1.png")
-
# attachments.inline['image-2.png'] = File.read("#{Rails.root}/app/assets/images/image-2.png")
-
# attachments.inline['image-3.png'] = File.read("#{Rails.root}/app/assets/images/image-3.png")
-
# attachments.inline['image-4.png'] = File.read("#{Rails.root}/app/assets/images/image-4.png")
-
# attachments.inline['image-5.png'] = File.read("#{Rails.root}/app/assets/images/image-5.png")
-
# attachments.inline['image-6.png'] = File.read("#{Rails.root}/app/assets/images/image-6.png")
-
1
mail(
-
to: @account.email,
-
from: "Whitebook <#{ENV['SMTP_USERNAME']}>",
-
subject: 'Welcome Email') do |format|
-
2
format.html { render 'account_block/email_validation_mailer/welcome_email' }
-
end
-
end
-
end
-
end
-
1
class ApplicationMailer < ActionMailer::Base
-
1
default from: "Whitebook <#{ENV['SMTP_USERNAME']}>"
-
1
layout 'mailer'
-
-
1
def send_mail(email, subject)
-
return if email.blank?
-
mail(to: email, subject: subject)
-
end
-
end
-
module BuilderBase
-
class ApplicationMailer < ::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockActivitylog
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockAddress
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockAdmin
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockAnalytics3
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockAppointmentManagement
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockAttachment
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockBulkUploading
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockCalendar
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockCatalogue
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockCategories
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockCfanimationsandtransition2
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockCfgooglephotosintegration2
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockCfinterfaceforbookpreview2
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockCfshiprocketintegration2
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockContentManagement
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockContentManagement
-
class ContentMailer < ApplicationMailer
-
end
-
end
-
module BxBlockCors
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockCouponCg
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockCoupons
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockCustomForm
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockCustomUserSubs
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockDashboard
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockDiscountsoffers
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockDownload
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockDragdropinterface
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockEmailNotifications
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockEmailNotifications
-
class EmailNotificationMailer < ApplicationMailer
-
def notification_email
-
@email_notification = params[:email_notification]
-
notification = @email_notification.notification
-
-
mail(to: @email_notification.send_to_email,
-
body: notification.contents,
-
subject: notification.headings)
-
-
@email_notification.touch(:sent_at)
-
end
-
end
-
end
-
module BxBlockFavourites
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockFedexIntegration
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockForgotPassword
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockForgotPassword
-
class EmailOtpMailer < ApplicationMailer
-
def otp_email
-
@otp = params[:otp]
-
@host = Rails.env.development? ? 'http://localhost:3000' : params[:host]
-
mail(
-
to: @otp.email,
-
from: 'builder.bx_dev@engineer.ai',
-
subject: 'Your OTP code') do |format|
-
format.html { render 'otp_email' }
-
end
-
end
-
end
-
end
-
module BxBlockGallery
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockHelpCentre
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockInvoicebilling
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockLandingpage3
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockLike
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockLocation
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockLogin
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockNotifications
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockOrderManagement
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockOrdersummary
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockPaymentAdmin
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockPlan
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockPosts
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockProfile
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockProjecttemplates
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockPushNotifications
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockReferrals
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockRefundmanagement
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockRequestManagement
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockReviews
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockRolesPermissions
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockScreenshoteditor0
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockSettings
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockShoppingCart
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
module BxBlockStatisticsreports
-
class ApplicationMailer < BuilderBase::ApplicationMailer
-
default from: 'from@example.com'
-
layout 'mailer'
-
end
-
end
-
class DraftMailer < ApplicationMailer
-
def draft_email(order)
-
@order = order
-
@account = @order.account
-
@book = BxBlockBook::Book.find_by(id: @order.book_id)
-
@token = BuilderJsonWebToken.encode @account.id
-
# attachments.inline['logo.jpg'] = File.read("#{Rails.root}/app/assets/images/logo.jpg")
-
attachments.inline['i-2.png'] = File.read("#{Rails.root}/app/assets/images/i-2.png")
-
# attachments.inline['image-3.jpeg'] = File.read("#{Rails.root}/app/assets/images/image-3.jpeg")
-
# attachments.inline['thumbnail.png'] = @book&.cover_image.present? ? File.read(ActiveStorage::Blob.service.send(:path_for, @book&.cover_image.key)) : File.read("#{Rails.root}/app/assets/images/thumbnail.png")
-
# attachments.inline['thumbnail.png'] = File.read("#{Rails.root}/app/assets/images/thumbnail.png")
-
attachments.inline['thumbnail.png'] = @book&.cover_image.attached? ? AccountBlock::DocxDownloadService.new(@book.cover_image).doc : File.read("#{Rails.root}/app/assets/images/thumbnail.png")
-
attachments.inline['i-5.png'] = File.read("#{Rails.root}/app/assets/images/i-5.png")
-
attachments.inline['i-6.png'] = File.read("#{Rails.root}/app/assets/images/i-6.png")
-
attachments.inline['df-1.png'] = File.read("#{Rails.root}/app/assets/images/df-1.png")
-
attachments.inline['df-2.png'] = File.read("#{Rails.root}/app/assets/images/df-2.png")
-
attachments.inline['df-3.png'] = File.read("#{Rails.root}/app/assets/images/df-3.png")
-
attachments.inline['df-4.png'] = File.read("#{Rails.root}/app/assets/images/df-4.png")
-
mail(
-
to: @account.email,
-
from: "Whitebook <#{ENV['SMTP_USERNAME']}>",
-
subject: 'Draft Email') do |format|
-
format.html { render 'draft' }
-
end
-
end
-
end
-
1
class OtpMailer < ApplicationMailer
-
1
def send_otp(email_record)
-
3
@email = email_record.email
-
3
@pin = email_record.pin
-
-
3
mail(
-
to: @email,
-
from: "Whitebook <#{ENV['SMTP_USERNAME']}>",
-
subject: "Otp Code"
-
)
-
end
-
end
-
1
class SignUpOtpMailer < ApplicationMailer
-
1
def signup_send_otp(email_record)
-
1
@email = email_record.email
-
1
@pin = email_record.pin
-
-
1
mail(
-
to: @email,
-
from: "Whitebook <#{ENV['SMTP_USERNAME']}>",
-
subject: "Otp Code"
-
)
-
end
-
end
-
class SystemMailer < ApplicationMailer
-
-
def order_create_info(order)
-
@order = order
-
attachments.inline['i-1.png'] = File.read("#{Rails.root}/app/assets/images/i-1.png")
-
attachments.inline['i-2.png'] = File.read("#{Rails.root}/app/assets/images/i-2.png")
-
attachments.inline['image-3.jpeg'] = File.read("#{Rails.root}/app/assets/images/image-3.jpeg")
-
attachments.inline['i-4.png'] = File.read("#{Rails.root}/app/assets/images/i-4.png")
-
attachments.inline['i-5.png'] = File.read("#{Rails.root}/app/assets/images/i-5.png")
-
attachments.inline['i-6.png'] = File.read("#{Rails.root}/app/assets/images/i-6.png")
-
# attachments.inline['thumbnail.png'] = File.read("#{Rails.root}/app/assets/images/thumbnail.png")
-
send_mail(get_account_email_address(order), "Order Placed")
-
end
-
-
def payment_done_info(order)
-
@order = order
-
send_mail(get_account_email_address(order), "Payment requested for Order")
-
end
-
-
def payment_failed_info(order)
-
@order = order
-
send_mail(get_account_email_address(order), "Payment Failed for Order")
-
end
-
-
def order_placed_info(order, json_response)
-
@order = order
-
@book = BxBlockBook::Book.find_by(id: @order.book_id)
-
attachments.inline['i-1.png'] = File.read("#{Rails.root}/app/assets/images/i-1.png")
-
attachments.inline['i-2.png'] = File.read("#{Rails.root}/app/assets/images/i-2.png")
-
# attachments.inline['image-3.jpeg'] = File.read("#{Rails.root}/app/assets/images/image-3.jpeg")
-
attachments.inline['i-4.png'] = File.read("#{Rails.root}/app/assets/images/i-4.png")
-
attachments.inline['i-5.png'] = File.read("#{Rails.root}/app/assets/images/i-5.png")
-
attachments.inline['i-6.png'] = File.read("#{Rails.root}/app/assets/images/i-6.png")
-
attachments.inline['thumbnail.png'] = @book&.cover_image&.attached? ? AccountBlock::DocxDownloadService.new(@book&.cover_image).doc : File.read("#{Rails.root}/app/assets/images/thumbnail.png")
-
# attachments.inline['thumbnail.png'] = @book&.cover_image.attached? ? File.read(ActiveStorage::Blob.service.send(:path_for, @book&.cover_image.key)) : File.read("#{Rails.root}/app/assets/images/thumbnail.png")
-
# attachments.inline['thumbnail.png'] = File.read("#{Rails.root}/app/assets/images/thumbnail.png")
-
@json_response = json_response
-
send_mail(get_account_email_address(order), "Order Placed")
-
end
-
-
def order_canceled_info(order, json_response)
-
@order = order
-
@json_response = json_response
-
send_mail(get_account_email_address(order), "Order Cancelled")
-
end
-
-
def payment_verified_info(order, order_transaction)
-
@order = order
-
@order_transaction = order_transaction
-
send_mail(get_account_email_address(order), "Payment Verified")
-
end
-
-
def send_order_update_info(order)
-
@order = order
-
send_mail(get_account_email_address(order), "Order update Status")
-
end
-
-
def get_account_email_address(order)
-
email = order&.account&.email
-
end
-
end
-
1
module AccountBlock
-
1
class Account < AccountBlock::ApplicationRecord
-
1
self.table_name = :accounts
-
1
self.primary_key = "id"
-
-
1
include Wisper::Publisher
-
-
# has_secure_password
-
# before_validation :parse_full_phone_number
-
# before_create :generate_api_key
-
1
has_one :blacklist_user, class_name: 'AccountBlock::BlackListUser', dependent: :destroy
-
1
has_many :books, class_name: 'BxBlockBook::Book'
-
1
has_many :user_offers, class_name: 'BxBlockDiscountsoffers::UserOffer'
-
1
has_many :orders, class_name: "BxBlockOrderManagement::Order"
-
1
has_many :addresses, class_name: "BxBlockAddress::Address"
-
1
has_many :order_transactions, class_name: "BxBlockOrderManagement::OrderTransaction", dependent: :delete_all
-
# after_save :set_black_listed_user
-
# after_save :activate_account
-
1
after_create :attach_shareable_link_to_account
-
1
has_one :referral_user, class_name: "BxBlockReferrals::ReferralUser"
-
1
has_one_attached :profile_picture
-
1
enum status: %i[regular suspended deleted]
-
-
3
scope :active, -> { where(activated: true) }
-
2
scope :existing_accounts, -> { where(status: ['regular', 'suspended']) }
-
-
1
def full_name
-
16
"#{first_name} #{last_name}"
-
end
-
-
1
private
-
-
1
def parse_full_phone_number
-
phone = Phonelib.parse(full_phone_number)
-
self.full_phone_number = phone.sanitized
-
self.country_code = phone.country_code
-
self.phone_number = phone.raw_national
-
end
-
-
1
def valid_phone_number
-
unless Phonelib.valid?(full_phone_number)
-
errors.add(:full_phone_number, "Invalid or Unrecognized Phone Number")
-
end
-
end
-
-
1
def generate_api_key
-
loop do
-
@token = SecureRandom.base64.tr('+/=', 'Qrt')
-
break @token unless Account.exists?(unique_auth_id: @token)
-
end
-
self.unique_auth_id = @token
-
end
-
-
1
def set_black_listed_user
-
if is_blacklisted_previously_changed?
-
if is_blacklisted
-
AccountBlock::BlackListUser.create(account_id: id)
-
else
-
blacklist_user.destroy
-
end
-
end
-
end
-
-
1
def activate_account
-
self.update_column(:activated, true) unless self.activated
-
end
-
-
1
def attach_shareable_link_to_account
-
108
o = [('a'..'z'), ('A'..'Z'), ('1'..'9')].map(&:to_a).flatten
-
1188
shared_code = (0...10).map { o[rand(o.length)] }.join
-
-
108
self.shared_link = check_enviroment + shared_code
-
108
self.save
-
end
-
-
1
def check_enviroment
-
108
if Rails.env.development?
-
'http://localhost:3000/'
-
else
-
108
"https://snapslikeapp2-89023-react-native.b89023.dev.eastus.az.svc.builder.cafe/"
-
end
-
end
-
end
-
end
-
1
module AccountBlock
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
1
module AccountBlock
-
1
class BlackListUser < AccountBlock::ApplicationRecord
-
1
self.table_name = :black_list_users
-
1
belongs_to :account, class_name: 'AccountBlock::Account'
-
-
1
def user_mobile_number
-
self.account.full_phone_number
-
end
-
-
1
def user_email
-
self.account.email
-
end
-
-
1
def user_type
-
self.account.user_type
-
end
-
end
-
end
-
1
module AccountBlock
-
1
class DashboardMediaFile < AccountBlock::ApplicationRecord
-
1
self.table_name = :dashboard_media_files
-
-
1
include ActiveStorageSupport::SupportForBase64
-
1
has_one_base64_attached :media_file
-
end
-
end
-
1
module AccountBlock
-
1
class DraftMailTimer < AccountBlock::ApplicationRecord
-
1
self.table_name = :draft_mail_timers
-
-
end
-
end
-
1
module AccountBlock
-
1
class EmailAccount < Account
-
1
include Wisper::Publisher
-
1
validates :email, presence: true
-
# validates :full_phone_number, presence: true
-
-
1
def self.create_stripe_customers(account)
-
stripe_customer = Stripe::Customer.create({
-
email: account.email
-
})
-
account.stripe_id = stripe_customer.id
-
account.save
-
end
-
end
-
end
-
1
module AccountBlock
-
1
class EmailOtp < ApplicationRecord
-
1
include Wisper::Publisher
-
-
1
self.table_name = :email_otps
-
-
1
validate :valid_email
-
1
validates :email, presence: true
-
-
1
before_create :generate_pin_and_valid_date
-
-
1
attr_reader :phone
-
-
1
def generate_pin_and_valid_date
-
6
self.pin = rand(1_000..9_999)
-
6
self.valid_until = Time.current + 5.minutes
-
6
self.activated = false
-
end
-
-
1
private
-
-
1
def valid_email
-
9
unless email =~ URI::MailTo::EMAIL_REGEXP
-
1
errors.add(:email, "Invalid email format")
-
end
-
end
-
end
-
end
-
1
module AccountBlock
-
1
class SmsAccount < Account
-
1
include Wisper::Publisher
-
1
validates :full_phone_number, uniqueness: true, presence: true
-
end
-
end
-
1
module AccountBlock
-
1
class SmsOtp < ApplicationRecord
-
1
self.table_name = :sms_otps
-
-
1
include Wisper::Publisher
-
-
1
before_validation :parse_full_phone_number
-
-
1
before_create :generate_pin_and_valid_date
-
1
after_create :send_pin_via_sms
-
-
1
validate :valid_phone_number
-
1
validates :full_phone_number, presence: true
-
-
1
attr_reader :phone
-
-
1
def generate_pin_and_valid_date
-
4
self.pin = rand(1_000..9_999)
-
4
self.valid_until = Time.current + 5.minutes
-
4
self.activated = false
-
end
-
-
1
def send_pin_via_sms
-
6
message = "Please use OTP - #{self.pin} to login to your Whitebook account.
-
OTP valid for 2 minutes.
-
Do not share this OTP with anyone for security reasons."
-
6
txt = BxBlockSms::SendSms.new("+#{self.full_phone_number}", message)
-
6
txt.call
-
end
-
-
1
private
-
-
1
def parse_full_phone_number
-
6
@phone = Phonelib.parse(full_phone_number)
-
6
self.full_phone_number = @phone.sanitized
-
end
-
-
1
def valid_phone_number
-
6
unless Phonelib.valid?(full_phone_number)
-
1
errors.add(:full_phone_number, "Invalid or Unrecognized Phone Number")
-
end
-
end
-
end
-
end
-
1
module AccountBlock
-
1
class SocialAccount < Account
-
1
include Wisper::Publisher
-
-
1
validates :email, uniqueness: true, presence: true
-
# validates :unique_auth_id, presence: true
-
1
after_validation :set_active
-
-
1
def set_active
-
4
self.activated = true
-
end
-
-
1
def self.create_from_omniauth(auth)
-
# Creates a new user only if it doesn't exist
-
where(email: auth.info.email).first_or_initialize do |user|
-
user.unique_auth_id = auth.uid
-
user.full_name = auth.info.name
-
user.email = auth.info.email
-
user.save
-
end
-
end
-
end
-
end
-
1
class AdminUser < ApplicationRecord
-
# Include default devise modules. Others available are:
-
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
-
1
devise :database_authenticatable,
-
:recoverable, :rememberable, :validatable
-
end
-
1
class ApplicationRecord < ActiveRecord::Base
-
1
self.abstract_class = true
-
end
-
1
module BuilderBase
-
1
class ApplicationRecord < ::ApplicationRecord
-
1
self.abstract_class = true
-
1
self.store_full_sti_class = false
-
end
-
end
-
module BxBlockActivitylog
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
1
module BxBlockAddress
-
1
class Address < BxBlockAddress::ApplicationRecord
-
1
self.table_name = :addresses
-
-
1
belongs_to :account, class_name: 'AccountBlock::Account',
-
foreign_key: 'addressble_id'
-
-
1
belongs_to :order, class_name: 'BxBlockOrderManagement::Order',
-
foreign_key: 'order_id'
-
# reverse_geocoded_by :latitude, :longitude
-
1
validates :email_address, :phone_number, :full_name, :pincode, :city, :address, :state, presence: true
-
1
has_one :shared_address, class_name: 'BxBlockAddress::SharedAddress', dependent: :destroy
-
1
accepts_nested_attributes_for :shared_address, allow_destroy: true
-
2
scope :active, -> { where(is_deleted: false) }
-
-
# enum address_type: { 'Home' => 0, 'Work' => 1, 'Other' => 2 }
-
# after_validation :reverse_geocode
-
# before_create :add_address_type
-
-
# private
-
# def add_address_type
-
# self.address_type = 'Home' unless self.address_type.present?
-
# end
-
end
-
end
-
1
module BxBlockAddress
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
1
module BxBlockAddress
-
1
class SharedAddress < ApplicationRecord
-
1
self.table_name = :shared_addresses
-
-
1
belongs_to :address, class_name: 'BxBlockAddress::Address', foreign_key: 'addressble_id'
-
end
-
end
-
1
module BxBlockAdmin
-
1
class AboutUs < BxBlockAdmin::ApplicationRecord
-
1
self.table_name = :about_us
-
1
self.primary_key = "id"
-
-
1
validates :description, presence: true
-
end
-
end
-
1
module BxBlockAdmin
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
1
module BxBlockAdmin
-
1
class PrivacyPolicy < BxBlockAdmin::ApplicationRecord
-
1
self.table_name = :privacy_policy
-
end
-
end
-
1
module BxBlockAdmin
-
1
class ReturnAndRefundPolicy < BxBlockAdmin::ApplicationRecord
-
1
self.table_name = :rnr_policy
-
end
-
end
-
1
module BxBlockAdmin
-
1
class TermsAndCondition < BxBlockAdmin::ApplicationRecord
-
1
self.table_name = :tnc
-
end
-
end
-
module BxBlockAnalytics3
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
module BxBlockAppointmentManagement
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
1
module BxBlockAppointmentManagement
-
1
class Availability < ApplicationRecord
-
-
1
include Wisper::Publisher
-
1
self.table_name = :availabilities
-
-
1
belongs_to :service_provider,
-
class_name: 'AccountBlock::Account', foreign_key: :service_provider_id
-
1
scope :sp_details, ->(sp_id, availability_date) {
-
find_by(service_provider_id: sp_id, availability_date: availability_date)
-
}
-
-
1
validates_presence_of :availability_date, :start_time, :end_time
-
# validate :check_date
-
7
validate :check_presence_of_days_slot, if: Proc.new{|availability| availability.new_record? }
-
-
1
before_save :set_params
-
-
1
scope :todays_availabilities, -> {
-
where(availability_date: Date.today.strftime('%d/%m/%y')).first
-
}
-
1
scope :filter_by_date, -> (date) {
-
where(availability_date: Date.parse(date).strftime('%d/%m/%y'))
-
}
-
1
scope :available_service_provider, -> (date) {
-
where(
-
availability_date: Date.parse(date).strftime('%d/%m/%y')
-
).order(:available_slots_count)&.first&.service_provider }
-
1
after_create :create_time_slots, :update_slot_count
-
-
1
def todays_online_hours
-
# Date will be in hour
-
full_day_slot = ((Time.parse(self.end_time) -Time.parse(self.start_time))/3600)
-
if self.unavailable_end_time.present? and self.unavailable_start_time.present?
-
unavailable_slot = ((Time.parse(self.unavailable_end_time) -
-
Time.parse(self.unavailable_start_time))/3600)
-
final_available_hours = full_day_slot - unavailable_slot
-
end
-
unavailable_slot.present? ? full_day_slot - unavailable_slot : full_day_slot
-
end
-
-
1
def slots_list
-
already_booked_slots = get_booked_slots(Date.strptime(self.availability_date, "%d/%m/%y"))
-
availability = self
-
return errors.add(
-
:availability, 'Service provider is unavailable for today'
-
) unless availability.present?
-
slots = BxBlockAppointmentManagement::TimeSlotsCalculator.new.calculate_time_slots(
-
availability.start_time, availability.end_time, 59
-
)
-
slots.each_with_index do |slot, index|
-
next if slot[:booked_status]
-
already_booked_slots.each do |booked_slot|
-
if (Time.parse(slot[:from])..Time.parse(slot[:to])).cover?(booked_slot[:start_time])
-
slot[:booked_status] = true
-
while (slots[index + 1].present? and (booked_slot[:start_time]..booked_slot[:end_time]).cover?(Time.parse(slots[index + 1][:from]))) do
-
slots[index + 1][:booked_status] = true
-
index +=1
-
break unless slots[index + 1].present?
-
end
-
end
-
end
-
end
-
slots
-
end
-
-
1
def update_slot_count
-
available_slots_count = self.slots_list.select{|time| time[:booked_status] == false }.count
-
self.update(available_slots_count: available_slots_count)
-
end
-
-
1
private
-
-
1
def check_date
-
errors.add(:invalid_date, 'Invalid Date, Please choose current date') unless
-
Date.parse(self.availability_date).today?
-
end
-
-
1
def get_booked_slots order_date
-
BookedSlot.where(
-
service_provider_id: self.service_provider,
-
booking_date: order_date
-
).map do |booked_slot|
-
{ start_time: booked_slot.start_time.to_time, end_time: booked_slot.end_time.to_time }
-
end
-
end
-
-
1
def check_presence_of_days_slot
-
slot = Availability.find_by(
-
service_provider_id: self.service_provider.id,
-
availability_date: Date.parse(self.availability_date).strftime('%d/%m/%y')
-
6
) if self.service_provider.present?
-
6
errors.add(:slot_error, 'You have already slot for the day') if slot.present?
-
end
-
-
1
def set_params
-
self.availability_date = Date.parse(self.availability_date).strftime('%d/%m/%y')
-
self.start_time = Time.parse(self.start_time).strftime("%I:%M %p")
-
self.end_time = Time.parse(self.end_time).strftime("%I:%M %p")
-
if self.unavailable_start_time.present?
-
self.unavailable_start_time = Time.parse(self.unavailable_start_time).strftime("%I:%M %p")
-
end
-
if self.unavailable_end_time.present?
-
self.unavailable_end_time = Time.parse(self.unavailable_end_time).strftime("%I:%M %p")
-
end
-
end
-
-
1
def create_time_slots
-
new_time_slots = TimeSlotsCalculator.new.calculate_time_slots(
-
self.start_time, self.end_time, 59
-
)
-
self.update_column("timeslots", new_time_slots)
-
end
-
end
-
end
-
1
module BxBlockAppointmentManagement
-
1
class BookedSlot < ApplicationRecord
-
-
1
self.table_name = :bx_block_appointment_management_booked_slots
-
-
1
belongs_to :service_provider, class_name: "AccountBlock::Account"
-
end
-
end
-
1
module BxBlockAttachment
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
1
module BxBlockAttachment
-
1
class Attachment < BxBlockAttachment::ApplicationRecord
-
1
self.table_name = :attachments
-
1
include Wisper::Publisher
-
-
1
has_one_attached :attachment
-
1
belongs_to :account, class_name: 'AccountBlock::Account'
-
1
after_create :default_values
-
1
scope :not_expired, -> {where('is_expired = ?',false)}
-
-
1
def default_values
-
self.colour = "Greyscale"
-
self.layout = "Portrait"
-
self.page_size = "A4"
-
self.print_sides = "Both"
-
self.scale = "Print all pages"
-
self.print_pages_from = 1
-
self.print_pages_to = 1
-
self.total_pages = 1
-
end
-
-
1
def self.attachment_expire
-
attachments = BxBlockAttachment::Attachment.where(
-
"created_at + '4 hours'::interval < ? AND is_expired =?", DateTime.now, false
-
)
-
if attachments.present?
-
attachments.each do |attachment|
-
broadcast(:attachment_expired, attachment)
-
attachment.update_attributes(:is_expired => true)
-
if attachment.attachment.attached?
-
attachment.attachment.purge
-
attachment.destroy
-
end
-
end
-
end
-
-
expired_attachments = BxBlockAttachment::Attachment.where(
-
"created_at + '4 hours'::interval < ? AND is_expired =?", DateTime.now, true
-
)
-
if expired_attachments.present?
-
expired_attachments.each do |at|
-
at.destroy
-
end
-
end
-
end
-
end
-
end
-
1
module BxBlockBook
-
1
class AdditionalPricePerPage < BxBlockBook::ApplicationRecord
-
1
self.table_name = :additional_price_per_pages
-
-
1
validates :additional_price, presence: true
-
-
1
before_destroy do
-
unless self.class.count > 1
-
errors.add :base, "atleast one per page price record should be present"
-
false
-
throw(:abort)
-
end
-
end
-
end
-
end
-
module BxBlockBook
-
class AlbumSize < BxBlockBook::ApplicationRecord
-
self.table_name = :album_sizes
-
end
-
end
-
1
module BxBlockBook
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
1
module BxBlockBook
-
1
class Book < BxBlockBook::ApplicationRecord
-
1
self.table_name = :table_books
-
1
belongs_to :account, class_name: 'AccountBlock::Account'
-
-
# has_many :photos, class_name: 'BxBlockGallery::Photo', dependent: :destroy
-
# accepts_nested_attributes_for :photos, reject_if: :all_blank, allow_destroy: true
-
-
1
enum book_status: [:pending, :completed]
-
-
1
include ActiveStorageSupport::SupportForBase64
-
1
has_many_base64_attached :images
-
1
has_many_base64_attached :compressed_images
-
1
has_one_base64_attached :cover_image
-
# validates :month, presence: true
-
# validates :year, presence: true
-
1
def test(image)
-
"data:image/jpeg\;base64\,\ #{Base64.encode64(AccountBlock::DocxDownloadService.new(image).doc)}".delete "\n"
-
end
-
end
-
end
-
1
module BxBlockBook
-
1
class BookColor < ApplicationRecord
-
1
self.table_name = :book_colors
-
-
1
validates :book_color, presence: true
-
1
validates :title_color, presence: true
-
1
validates :logo_color, presence: true
-
-
1
before_destroy do
-
unless self.class.count > 1
-
errors.add :base, "atleast one color record should be present"
-
false
-
throw(:abort)
-
end
-
end
-
end
-
end
-
1
module BxBlockBook
-
1
class BookSize < BxBlockBook::ApplicationRecord
-
1
self.table_name = :book_sizes
-
end
-
end
-
1
module BxBlockBook
-
1
class Contribution < BxBlockBook::ApplicationRecord
-
1
self.table_name = :contributions
-
-
1
include ActiveStorageSupport::SupportForBase64
-
1
has_many_base64_attached :images
-
end
-
end
-
module BxBlockBook
-
class ContributionImage < BxBlockBook::ApplicationRecord
-
self.table_name = :contribution_images
-
end
-
end
-
1
module BxBlockBook
-
1
class DeliveryCharge < BxBlockBook::ApplicationRecord
-
1
self.table_name = :delivery_charges
-
1
validates :charge, presence: true, uniqueness: true
-
-
1
before_destroy do
-
unless self.class.count > 1
-
errors.add :base, "atleast one delivery charge record should be present"
-
false
-
throw(:abort)
-
end
-
end
-
end
-
end
-
1
module BxBlockBook
-
1
class ImageLimit < BxBlockBook::ApplicationRecord
-
1
self.table_name = :image_limits
-
-
end
-
end
-
1
module BxBlockBook
-
1
class Price < BxBlockBook::ApplicationRecord
-
1
self.table_name = :prices
-
-
1
validates :cover_type, presence: true, inclusion: { in: ['soft cover', 'hard cover'], message: "cover type only hard cover and soft cover accepted" }
-
1
validates :price, presence: true
-
1
validates :book_size, presence: true
-
1
validates :min_limit, presence: true
-
1
validates :max_limit, presence: true
-
1
validate :valid_min_limit_max_limit
-
-
1
before_destroy do
-
unless self.class.count > 1
-
errors.add :base, "atleast one price record should be present"
-
false
-
throw(:abort)
-
end
-
end
-
-
1
private
-
-
1
def valid_min_limit_max_limit
-
46
if (min_limit > max_limit)
-
errors.add(:max_limit, "must be greate than min limit")
-
false
-
throw(:abort)
-
end
-
end
-
end
-
end
-
1
module BxBlockBulkUploading
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
1
module BxBlockBulkUploading
-
1
class Attachment < BxBlockBulkUploading::ApplicationRecord
-
1
self.table_name = :attachments
-
1
include Wisper::Publisher
-
-
1
has_one_attached :attachment
-
1
belongs_to :account, class_name: 'AccountBlock::Account'
-
end
-
end
-
module BxBlockCalendar
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
module BxBlockCatalogue
-
class Brand < BxBlockCatalogue::ApplicationRecord
-
self.table_name = :brands
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class Catalogue < BxBlockCatalogue::ApplicationRecord
-
1
PAGE = 1
-
1
PER_PAGE = 10
-
-
1
self.table_name = :catalogues
-
-
1
enum availability: %i[in_stock out_of_stock]
-
-
1
belongs_to :category,
-
class_name: 'BxBlockCategories::Category',
-
foreign_key: 'category_id'
-
-
1
belongs_to :sub_category,
-
class_name: 'BxBlockCategories::SubCategory',
-
foreign_key: 'sub_category_id'
-
-
1
belongs_to :brand, optional: true
-
-
1
has_many :reviews, dependent: :destroy
-
1
has_many :catalogue_variants, dependent: :destroy
-
1
has_and_belongs_to_many :tags, join_table: :catalogues_tags
-
-
1
has_many_attached :images, dependent: :destroy
-
-
1
accepts_nested_attributes_for :catalogue_variants, allow_destroy: true
-
-
1
def average_rating
-
return 0 if reviews.size.zero?
-
-
total_rating = 0
-
reviews.each do |r|
-
total_rating += r.rating
-
end
-
total_rating.to_f / reviews.size.to_f
-
end
-
end
-
end
-
-
1
module BxBlockCatalogue
-
1
class CatalogueVariant < BxBlockCatalogue::ApplicationRecord
-
1
self.table_name = :catalogue_variants
-
-
1
belongs_to :catalogue
-
1
belongs_to :catalogue_variant_color, optional: true
-
1
belongs_to :catalogue_variant_size, optional: true
-
-
1
has_many_attached :images, dependent: :destroy
-
end
-
end
-
module BxBlockCatalogue
-
class CatalogueVariantColor < BxBlockCatalogue::ApplicationRecord
-
self.table_name = :catalogue_variant_colors
-
end
-
end
-
module BxBlockCatalogue
-
class CatalogueVariantSize < BxBlockCatalogue::ApplicationRecord
-
self.table_name = :catalogue_variant_sizes
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class CataloguesTag < BxBlockCatalogue::ApplicationRecord
-
1
self.table_name = :catalogues_tags
-
-
1
belongs_to :catalogue
-
1
belongs_to :tag
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class Review < BxBlockCatalogue::ApplicationRecord
-
1
self.table_name = :catalogue_reviews
-
-
1
belongs_to :catalogue
-
end
-
end
-
1
module BxBlockCatalogue
-
1
class Tag < BxBlockCatalogue::ApplicationRecord
-
1
self.table_name = :tags
-
-
1
has_and_belongs_to_many :catalogue, join_table: :catalogues_tags
-
end
-
end
-
1
module BxBlockCategories
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
1
module BxBlockCategories
-
1
class Category < BxBlockCategories::ApplicationRecord
-
1
self.table_name = :categories
-
-
1
mount_uploader :light_icon, ImageUploader
-
1
mount_uploader :light_icon_active, ImageUploader
-
1
mount_uploader :light_icon_inactive, ImageUploader
-
1
mount_uploader :dark_icon, ImageUploader
-
1
mount_uploader :dark_icon_active, ImageUploader
-
1
mount_uploader :dark_icon_inactive, ImageUploader
-
-
1
has_and_belongs_to_many :sub_categories,
-
join_table: :categories_sub_categories, dependent: :destroy
-
-
1
has_many :contents, class_name: "BxBlockContentmanagement::Content", dependent: :destroy
-
1
has_many :ctas, class_name: "BxBlockCategories::Cta", dependent: :nullify
-
-
1
has_many :user_categories, class_name: "BxBlockCategories::UserCategory",
-
join_table: "user_categoeries", dependent: :destroy
-
1
has_many :accounts, class_name: "AccountBlock::Account", through: :user_categories,
-
join_table: "user_categoeries"
-
-
1
validates :name, uniqueness: true, presence: true
-
1
validates_uniqueness_of :identifier, allow_blank: true
-
-
1
enum identifier: ["k12", "higher_education", "govt_job", "competitive_exams", "upskilling"]
-
end
-
end
-
1
module BxBlockCategories
-
1
class Cta < ApplicationRecord
-
1
self.table_name = :cta
-
-
1
belongs_to :category
-
-
1
mount_uploader :long_background_image, ImageUploader
-
1
mount_uploader :square_background_image, ImageUploader
-
-
1
enum text_alignment: ["centre", "left", "right"]
-
1
enum button_alignment: ["centre", "left", "right"], _suffix: true
-
-
1
validates :headline, :text_alignment, presence: true, if: -> { self.is_text_cta }
-
1
validates :button_text, :redirect_url, :button_alignment, presence: true,
-
if: -> { self.has_button }
-
-
1
def name
-
headline
-
end
-
end
-
end
-
1
module BxBlockCategories
-
1
class SubCategory < BxBlockCategories::ApplicationRecord
-
1
self.table_name = :sub_categories
-
-
1
has_and_belongs_to_many :categories, join_table: :categories_sub_categories, dependent: :destroy
-
1
belongs_to :parent, class_name: "BxBlockCategories::SubCategory", optional: true
-
1
has_many :sub_categories, class_name: "BxBlockCategories::SubCategory",
-
foreign_key: :parent_id, dependent: :destroy
-
1
has_many :user_sub_categories, class_name: "BxBlockCategories::UserSubCategory",
-
join_table: "user_sub_categoeries", dependent: :destroy
-
1
has_many :accounts, class_name: "AccountBlock::Account", through: :user_sub_categories,
-
join_table: "user_sub_categoeries"
-
-
1
validates :name, uniqueness: true, presence: true
-
1
validate :check_parent_categories
-
-
1
private
-
-
1
def check_parent_categories
-
2
if categories.blank? && parent.blank?
-
2
errors.add(:base, "Please select categories or a parent.")
-
end
-
end
-
-
end
-
end
-
1
module BxBlockCategories
-
1
class UserCategory < ApplicationRecord
-
1
self.table_name = :user_categories
-
-
1
belongs_to :account, class_name: "AccountBlock::Account"
-
1
belongs_to :category
-
end
-
end
-
1
module BxBlockCategories
-
1
class UserSubCategory < ApplicationRecord
-
1
self.table_name = :user_sub_categories
-
-
1
belongs_to :account, class_name: "AccountBlock::Account"
-
1
belongs_to :sub_category
-
end
-
end
-
module BxBlockCfanimationsandtransition2
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
module BxBlockCfgooglephotosintegration2
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
module BxBlockCfinterfaceforbookpreview2
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
module BxBlockCfshiprocketintegration2
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
module BxBlockContentManagement
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
1
module BxBlockContentManagement
-
1
class Audio < ApplicationRecord
-
1
self.table_name = :audios
-
1
mount_uploader :audio, AudioUploader
-
-
# Associations
-
1
belongs_to :attached_item, polymorphic: true
-
-
# Validations
-
1
validates_presence_of :audio
-
end
-
end
-
1
module BxBlockContentManagement
-
1
class AudioPodcast < ApplicationRecord
-
1
include Contentable
-
-
1
self.table_name = :audio_podcasts
-
-
1
validates_presence_of :heading
-
-
1
has_one :image, as: :attached_item, dependent: :destroy
-
1
has_one :audio, as: :attached_item, dependent: :destroy
-
-
1
accepts_nested_attributes_for :image, allow_destroy: true
-
1
accepts_nested_attributes_for :audio, allow_destroy: true
-
-
1
def name
-
heading
-
end
-
-
1
def image_url
-
image.image_url if image.present?
-
end
-
-
1
def video_url
-
nil
-
end
-
-
1
def audio_url
-
audio.audio_url if audio.present?
-
end
-
-
1
def study_material_url
-
nil
-
end
-
end
-
-
end
-
1
module BxBlockContentManagement
-
1
class Author < ApplicationRecord
-
1
self.table_name = :authors
-
1
has_many :contents, class_name: "BxBlockContentManagement::Content", dependent: :destroy
-
1
validates :name, :bio, presence: true
-
1
validates :bio, :length => {
-
:maximum => 500, :too_long => "should not greater then %{count} words"
-
}
-
1
has_one :image, as: :attached_item, dependent: :destroy
-
-
1
accepts_nested_attributes_for :image, allow_destroy: true
-
end
-
end
-
1
module BxBlockContentManagement
-
1
class Bookmark < ApplicationRecord
-
1
self.table_name = :bookmarks
-
1
belongs_to :account, class_name: "AccountBlock::Account"
-
1
belongs_to :content, class_name: "BxBlockContentManagement::Content"
-
1
validates_presence_of :account_id, :content_id
-
1
validates :account_id, uniqueness: { scope: :content_id, message: "content with this account is already taken"}
-
end
-
end
-
1
module BxBlockContentManagement
-
1
class Content < ApplicationRecord
-
1
self.table_name = :contents
-
-
1
MAX_TAG_CHARACTERS = 35
-
-
1
belongs_to :category, class_name: 'BxBlockCategories::Category', foreign_key: 'category_id'
-
1
belongs_to :sub_category, class_name: 'BxBlockCategories::SubCategory', foreign_key: 'sub_category_id'
-
1
belongs_to :content_type, class_name: 'BxBlockContentManagement::ContentType', foreign_key: 'content_type_id'
-
1
belongs_to :language, class_name: 'BxBlockLanguageOptions::Language', foreign_key: 'language_id'
-
1
belongs_to :contentable, polymorphic: true, inverse_of: :contentable, autosave: true, dependent: :destroy
-
1
belongs_to :author, class_name: 'BxBlockContentManagement::Author', optional: true
-
1
has_many :bookmarks, class_name: "BxBlockContentManagement::Bookmark", dependent: :destroy
-
1
has_many :account_bookmarks, class_name: "AccountBlock::Account", through: :bookmarks, source: :account
-
-
1
validates :author_id, presence: true, if: -> { self.content_type&.blog? }
-
1
validates :publish_date, presence: true, if: ->{ self.publish? }
-
1
validates :status, presence: true
-
1
validate :validate_publish_date, on: :update
-
1
validate :validate_status, on: :update
-
1
validate :validate_content_type, on: :update
-
1
validate :validate_approve_status, on: :update
-
1
validate :max_tag_char_length
-
1
validates :feedback, presence: true, if: -> { self.rejected? }
-
-
1
scope :operations_l1_content, -> { where(review_status: ["pending", "rejected", "submit_for_review"]) }
-
1
scope :submit_for_review_l1_content, -> { where(review_status: ["submit_for_review"]) }
-
-
1
attr_accessor :current_user_id
-
-
-
1
after_initialize :set_defaults
-
-
1
accepts_nested_attributes_for :contentable
-
-
1
scope :non_archived, -> { where(archived: false) }
-
1
scope :archived, -> { where(archived: true) }
-
-
1
searchkick
-
-
1
acts_as_taggable_on :tags
-
-
1
enum status: ["draft", "publish", "disable"]
-
-
1
enum review_status: ["pending", "submit_for_review", "approve", "rejected"]
-
-
1
scope :published, -> {publish.where("publish_date < ?", DateTime.current)}
-
1
scope :blogs_content, -> { joins(:content_type).where(content_types: {identifier: 'blog'}) }
-
1
scope :filter_content, ->(categories, sub_categories, content_types) {
-
where(category: categories, sub_category: sub_categories, content_type: content_types)
-
}
-
1
scope :in_review, -> { where(review_status: "submit_for_review")}
-
-
1
def contentable_attributes=(attributes)
-
self.contentable_type = content_type&.type_class
-
if self.contentable_type
-
some_contentable = self.contentable_type.constantize.find_or_initialize_by(id: self.contentable_id)
-
some_contentable.attributes = attributes
-
self.contentable = some_contentable
-
end
-
end
-
-
1
def name
-
contentable&.name
-
end
-
-
1
def description
-
contentable&.description
-
end
-
-
1
def image
-
contentable&.image_url
-
end
-
-
1
def video
-
contentable&.video_url
-
end
-
-
1
def audio
-
contentable&.audio_url
-
end
-
-
1
def study_material
-
contentable&.study_material_url
-
end
-
-
1
def search_data
-
attributes.merge(
-
category_name: self.category.name,
-
sub_category_name: self.sub_category.name,
-
language_name: self.language.name,
-
content_type_name: self.content_type.name,
-
contentable: self.contentable,
-
tags: self.tags.map(&:name).join(" ")
-
)
-
end
-
-
1
private
-
-
1
def max_tag_char_length
-
self.tag_list.each do |tag|
-
if tag.length > MAX_TAG_CHARACTERS
-
errors[:tag] << "#{tag} must be shorter than #{MAX_TAG_CHARACTERS} characters maximum"
-
end
-
end
-
end
-
-
1
def validate_status
-
if self.draft? && will_save_change_to_status?
-
errors.add(:status, "can't be change to draft.")
-
end
-
end
-
-
1
def validate_content_type
-
errors.add(:content_type_id, "can't be updated") if will_save_change_to_content_type_id?
-
end
-
-
1
def validate_publish_date
-
if status_in_database == 'publish' && will_save_change_to_publish_date? && publish_date_in_database.present? &&
-
publish_date_in_database <= DateTime.current
-
errors.add(:publish_date, "can't be changed after published.")
-
end
-
end
-
-
1
def set_defaults
-
2
self.status ||= "draft"
-
end
-
-
1
def validate_approve_status
-
if will_save_change_to_status? && self.publish? && !self.approve?
-
errors.add(:status, "can't be published if content was not approved.")
-
end
-
end
-
end
-
end
-
1
module BxBlockContentManagement
-
1
class ContentText < ApplicationRecord
-
1
include Contentable
-
-
1
self.table_name = :content_texts
-
-
1
validates_presence_of :headline, :content
-
-
1
has_many :images, as: :attached_item, dependent: :destroy
-
1
has_many :videos, as: :attached_item, dependent: :destroy, class_name: 'BxBlockContentManagement::Video'
-
1
accepts_nested_attributes_for :videos, allow_destroy: true
-
1
accepts_nested_attributes_for :images, allow_destroy: true
-
-
1
def name
-
headline
-
end
-
-
1
def description
-
content
-
end
-
-
1
def image_url
-
images.first.image_url if images.present?
-
end
-
-
1
def video_url
-
videos.first.video_url if videos.present?
-
end
-
-
1
def audio_url
-
nil
-
end
-
-
1
def study_material_url
-
nil
-
end
-
end
-
end
-
1
module BxBlockContentManagement
-
1
class ContentType < ApplicationRecord
-
1
self.inheritance_column = nil
-
1
self.table_name = :content_types
-
-
TYPE_MAPPINGS = {
-
1
"Text" => BxBlockContentManagement::ContentText.name,
-
"Videos" => BxBlockContentManagement::ContentVideo.name,
-
"Live Stream" => BxBlockContentManagement::LiveStream.name,
-
"AudioPodcast" => BxBlockContentManagement::AudioPodcast.name,
-
"Test" => BxBlockContentManagement::Test.name,
-
"Epub" => BxBlockContentManagement::Epub.name
-
}.freeze
-
-
1
validates_presence_of :name, :type
-
1
validates_uniqueness_of :name, case_sensitive: false
-
1
validates_uniqueness_of :identifier, allow_blank: true
-
-
1
has_many :contents, class_name: "BxBlockContentManagement::Content", dependent: :destroy
-
1
has_and_belongs_to_many :partners, class_name: 'BxBlockRolesPermissions::Partner',
-
join_table: :content_types_partners, dependent: :destroy
-
-
-
1
enum type: ["Text", "Videos", "Live Stream", "AudioPodcast", "Test", "Epub"]
-
-
1
enum identifier: ["news_article", "audio_podcast", "blog", "live_streaming", "quiz", "assessment",
-
"study_material", "video_short", "video_full"]
-
-
1
def type_class
-
TYPE_MAPPINGS[type]
-
end
-
end
-
end
-
1
module BxBlockContentManagement
-
1
class ContentVideo < ApplicationRecord
-
1
include Contentable
-
-
1
self.table_name = :content_videos
-
-
1
validates_presence_of :headline
-
-
1
has_one :video, as: :attached_item, dependent: :destroy, class_name: 'BxBlockContentManagement::Video'
-
1
has_one :image, as: :attached_item, dependent: :destroy
-
1
accepts_nested_attributes_for :video, allow_destroy: true
-
1
accepts_nested_attributes_for :image, allow_destroy: true
-
-
1
def name
-
headline
-
end
-
-
1
def image_url
-
image.image_url if image.present?
-
end
-
-
1
def video_url
-
video.video_url if video.present?
-
end
-
-
1
def audio_url
-
nil
-
end
-
-
1
def study_material_url
-
nil
-
end
-
-
1
private
-
-
1
def validate_video_short_length
-
if self.video.present? and self.video.video.present?
-
errors.add(:video, "can't be more than 30 seconds") if get_time_duration(self.video.video) >= 30
-
end
-
end
-
-
1
def validate_video_full_length
-
if self.video.present? and self.video.video.present?
-
errors.add(:video, "can't be less than 30 seconds") if get_time_duration(self.video.video) < 30
-
end
-
end
-
-
1
def get_time_duration(video)
-
movie = FFMPEG::Movie.new(video.current_path)
-
movie.duration
-
end
-
end
-
end
-
1
module BxBlockContentManagement
-
1
class CustomEmail < ApplicationRecord
-
1
self.table_name = :custom_emails
-
-
1
enum email_type: %i[welcome_email activation_email draft_email order_placed_info]
-
1
enum valid_for: %i[new_users old_users all_users]
-
1
has_one_attached :image1
-
1
has_one_attached :image2
-
1
has_one_attached :image3
-
1
has_one_attached :image4
-
1
has_one_attached :image5
-
1
has_one_attached :image6
-
1
has_one_attached :image7
-
1
has_one_attached :image8
-
end
-
end
-
1
module BxBlockContentManagement
-
1
class Epub < ApplicationRecord
-
1
include Contentable
-
-
1
self.table_name = :epubs
-
-
1
validates_presence_of :heading, :description
-
-
1
has_many :pdfs, class_name: 'BxBlockContentManagement::Pdf', as: :attached_item, dependent: :destroy
-
1
accepts_nested_attributes_for :pdfs, allow_destroy: true
-
-
1
def name
-
heading
-
end
-
-
1
def image_url
-
nil
-
end
-
-
1
def video_url
-
nil
-
end
-
-
1
def audio_url
-
nil
-
end
-
-
1
def study_material_url
-
pdfs.first.pdf_url if pdfs.present?
-
end
-
end
-
end
-
1
module BxBlockContentManagement
-
1
class Exam < ApplicationRecord
-
1
self.table_name = :exams
-
-
1
validates_presence_of :heading, :to, :from
-
-
1
validate :check_to_and_from
-
-
1
def name
-
heading
-
end
-
-
1
private
-
-
1
def check_to_and_from
-
1
if self.to.present? && self.from.present? && self.to < self.from
-
errors.add(:from, "can't be greater than to")
-
end
-
end
-
end
-
end
-
1
module BxBlockContentManagement
-
1
class Follow < ApplicationRecord
-
1
self.table_name = :follows
-
1
belongs_to :account, class_name: "AccountBlock::Account"
-
1
validates :account_id, uniqueness: { scope: :content_provider_id,
-
message: "content provider with this account is already taken"}
-
end
-
end
-
1
module BxBlockContentManagement
-
1
class Image < ApplicationRecord
-
1
self.table_name = :images
-
1
mount_uploader :image, ImageUploader
-
-
# Associations
-
1
belongs_to :attached_item, polymorphic: true
-
-
# Validations
-
1
validates_presence_of :image
-
end
-
end
-
1
module BxBlockContentManagement
-
1
class LiveStream < ApplicationRecord
-
1
include Contentable
-
-
1
self.table_name = :live_streams
-
-
1
validates_presence_of :headline
-
-
1
def name
-
headline
-
end
-
-
1
def image_url
-
nil
-
end
-
-
1
def video_url
-
nil
-
end
-
-
1
def audio_url
-
nil
-
end
-
-
1
def study_material_url
-
nil
-
end
-
end
-
end
-
1
module BxBlockContentManagement
-
1
class Pdf < ApplicationRecord
-
1
self.table_name = :pdfs
-
1
mount_uploader :pdf, PdfUploader
-
-
# Associations
-
1
belongs_to :attached_item, polymorphic: true
-
-
# Validations
-
1
validates_presence_of :pdf
-
end
-
end
-
1
module BxBlockContentManagement
-
1
class Test < ApplicationRecord
-
1
include Contentable
-
-
1
self.table_name = :tests
-
-
1
validates_presence_of :headline, :description
-
-
1
def name
-
headline
-
end
-
-
1
def image_url
-
nil
-
end
-
-
1
def video_url
-
nil
-
end
-
-
1
def audio_url
-
nil
-
end
-
-
1
def study_material_url
-
nil
-
end
-
-
-
end
-
end
-
1
module BxBlockContentManagement
-
1
class Video < ApplicationRecord
-
1
self.table_name = :videos
-
1
mount_uploader :video, VideoUploader
-
-
# Associations
-
1
belongs_to :attached_item, polymorphic: true
-
-
# Validations
-
1
validates_presence_of :video
-
end
-
end
-
module BxBlockCors
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
1
module BxBlockCouponCg
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
1
module BxBlockCouponCg
-
1
class CouponCode < BxBlockCouponCg::ApplicationRecord
-
1
self.table_name = :coupon_codes
-
-
DISCOUNT_TYPE = {
-
1
flat: 'flat',
-
percentage: 'percentage'
-
}.freeze
-
-
1
MAX_CART_VALUE = 100_000
-
1
MAX_DISCOUNT_VALUE = 100_000
-
-
1
validates :title, length: { maximum: 50 }, presence: true
-
1
validates :description, length: { maximum: 200 }
-
1
validates :code, length: { maximum: 50 }, presence: true
-
1
validates :code, uniqueness: true
-
-
1
validates :discount_type, acceptance: {
-
accept: [DISCOUNT_TYPE[:flat], DISCOUNT_TYPE[:percentage]]
-
}
-
1
validate :min_cart_value_not_negative
-
1
validate :max_cart_value_less_max_value
-
1
validate :discount_value
-
-
1
def min_cart_value_not_negative
-
if min_cart_value.negative?
-
errors.add(:min_cart_value, "Can't be less than zero")
-
end
-
end
-
-
1
def max_cart_value_less_max_value
-
if max_cart_value > MAX_CART_VALUE
-
errors.add(:max_cart_value, "Can't be more than #{MAX_CART_VALUE}")
-
end
-
end
-
-
1
def discount_value
-
if discount.negative? || discount > MAX_DISCOUNT_VALUE
-
errors.add(:discount, 'Discount value is out of bounds')
-
end
-
end
-
end
-
end
-
module BxBlockCoupons
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
1
module BxBlockCoupons
-
1
class ComboOffer < ApplicationRecord
-
1
self.table_name = :combo_offers
-
-
1
has_and_belongs_to_many :sub_categories,
-
class_name: 'BxBlockCategories::SubCategory',
-
dependent: :destroy, join_table: 'offer_services'
-
1
has_one_attached :logo
-
-
1
validates_presence_of :name, :discount_percentage, :offer_start_date, :offer_end_date
-
1
validates_uniqueness_of :name
-
-
-
1
before_save :calc_final_price
-
-
1
private
-
-
1
def calc_final_price
-
original_price = self.sub_categories.map{|a|a.price}.sum
-
self.final_price = original_price - ((original_price * self.discount_percentage) / 100)
-
end
-
-
1
def suitable_service_provider
-
BxBlockRolesPermissions::Role.find_by_name('Merchant').accounts self.sub_categories.ids
-
end
-
end
-
end
-
1
module BxBlockCoupons
-
1
class Coupon < ApplicationRecord
-
1
self.table_name = :coupons
-
-
1
include Wisper::Publisher
-
-
1
has_many :coupon_services, class_name: "BxBlockCoupons::CouponService", dependent: :destroy
-
1
accepts_nested_attributes_for :coupon_services
-
-
1
validates_presence_of :name, :discount, :coupon_type, :min_order, :status, :max_discount
-
1
validates_uniqueness_of :name
-
1
validate :check_discount_percent
-
-
1
enum coupon_type: {"up_to" => 0, "flat" => 1}
-
1
enum status: { 'activated' => 1, 'expired' => 2 }
-
-
-
1
private
-
1
def check_discount_percent
-
7
errors.add(:discount_percent, 'Invalid Discount Percent') if self.discount.to_i > 100
-
end
-
end
-
end
-
1
module BxBlockCoupons
-
1
class CouponService < ApplicationRecord
-
1
self.table_name = :coupon_services
-
-
1
belongs_to :coupon, class_name: 'BxBlockCoupons::Coupon'
-
1
belongs_to :sub_categories, class_name: 'BxBlockCategories::SubCategory'
-
end
-
end
-
-
1
module BxBlockCoupons
-
1
class OrderComboOffer < ApplicationRecord
-
1
self.table_name = :order_combo_offers
-
1
belongs_to :combo_offer
-
1
belongs_to :order, class_name: "BxBlockShoppingCart::Order"
-
end
-
end
-
module BxBlockCoupons
-
class RefferalCoupon < AccountBlock::ApplicationRecord
-
self.table_name = :refferal_coupons
-
end
-
end
-
1
module BxBlockCustomForm
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
1
module BxBlockCustomForm
-
1
class SellerAccount < BxBlockCustomForm::ApplicationRecord
-
1
self.table_name = :seller_accounts
-
1
acts_as_mappable :default_units => :kms,
-
:default_formula => :sphere,
-
:distance_field_name => :distance,
-
:lat_column_name => :lat,
-
:lng_column_name => :long
-
-
1
belongs_to :account, class_name: "AccountBlock::Account"
-
end
-
end
-
module BxBlockCustomUserSubs
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
1
module BxBlockCustomUserSubs
-
1
class Subscription < ApplicationRecord
-
1
has_many :user_subscriptions,
-
class_name: 'BxBlockCustomUserSubs::UserSubscription', dependent: :delete_all
-
1
has_many :accounts, through: :user_subscriptions, class_name: 'AccountBlock::Account'
-
1
validates :name, presence: true
-
1
validates :valid_up_to, presence: true
-
-
1
has_one_attached :image
-
end
-
end
-
1
module BxBlockCustomUserSubs
-
1
class UserSubscription < ApplicationRecord
-
1
self.table_name = :user_subscriptions
-
1
belongs_to :account, class_name: "AccountBlock::Account"
-
1
belongs_to :subscription , class_name: "BxBlockCustomUserSubs::Subscription"
-
end
-
end
-
module BxBlockDashboard
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
module BxBlockDashboard
-
class Dashboard < BxBlockDashboard::ApplicationRecord
-
self.table_name = :dashboards
-
end
-
end
-
-
1
module BxBlockDiscountsoffers
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
1
module BxBlockDiscountsoffers
-
1
class Offer < BxBlockDiscountsoffers::ApplicationRecord
-
1
self.table_name = :offers
-
-
53
validates :code, uniqueness: true, if: -> {coupon_type != "referral"}
-
1
validates :discount_type, presence: true, inclusion: { in: ['flat', 'percentage'], message: "discount type only flat and percentage accepted" }
-
-
1
validates :discount_type, presence: true
-
1
validates :min_cart_value, presence: true
-
1
validates :discount, presence: true
-
1
validates :title, presence: true
-
# validates :description, presence: true, if: -> {coupon_type != referral?}
-
1
validates :valid_from, presence: true
-
1
validates :valid_to, presence: true
-
1
validate :valid_date_range_required
-
-
1
enum valid_for: [:new_users, :old_users, :all_users]
-
1
enum coupon_type: [:normal, :referral, :share_order_code, :specfic_user]
-
1
enum combine_with_other_offer: [:inactive, :active]
-
-
1
private
-
-
1
def valid_date_range_required
-
51
if (valid_from && valid_to) && (valid_to < valid_from)
-
errors.add(:valid_to, "must be later than valid_from")
-
end
-
end
-
-
-
1
def coupon_type_validation
-
if self.coupon_type != "referral"
-
offer_code = BxBlockDiscountsoffers::Offer.find_by(code: self.code)
-
errors.add("Code can't be blank") if self.code.nil?
-
errors.add("description can't be blank") if self.description.nil?
-
end
-
end
-
-
end
-
end
-
-
1
module BxBlockDiscountsoffers
-
1
class UserOffer < BxBlockDiscountsoffers::ApplicationRecord
-
1
self.table_name = :user_offers
-
-
1
belongs_to :account, class_name: 'AccountBlock::Account'
-
1
belongs_to :offer, class_name: 'BxBlockDiscountsoffers::Offer'
-
-
1
validates :code, presence: true
-
-
1
enum coupon_type: [:normal, :referral, :share_order_code, :specfic_user]
-
end
-
end
-
-
module BxBlockDownload
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
module BxBlockDragdropinterface
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
module BxBlockEmailNotifications
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
1
module BxBlockEmailNotifications
-
1
class EmailNotification < ApplicationRecord
-
1
self.table_name = :email_notifications
-
1
belongs_to :notification , class_name: 'BxBlockNotifications::Notification'
-
end
-
end
-
1
module BxBlockFavourites
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
1
module BxBlockFavourites
-
1
class Favourite < BxBlockFavourites::ApplicationRecord
-
1
self.table_name = :favourites
-
-
1
belongs_to :favouriteable, polymorphic: true
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: addressables
-
#
-
# id :bigint not null, primary key
-
# shipment_id :bigint not null
-
# address :text
-
# address2 :text
-
# city :string
-
# country :string
-
# email :string
-
# name :string
-
# phone :string
-
# instructions :text
-
# type :string
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
#
-
1
module BxBlockFedexIntegration
-
1
class Addressable < BxBlockFedexIntegration::ApplicationRecord
-
1
self.table_name = :addressables
-
-
1
belongs_to :shipment, class_name: "BxBlockFedexIntegration::Shipment"
-
1
has_one :arrival_window,
-
class_name: "BxBlockFedexIntegration::ArrivalWindow", dependent: :destroy
-
1
has_one :coordinate,
-
class_name: "BxBlockFedexIntegration::Coordinate", dependent: :destroy
-
-
1
accepts_nested_attributes_for :arrival_window, :coordinate
-
end
-
end
-
1
module BxBlockFedexIntegration
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: arrival_windows
-
#
-
# id :bigint not null, primary key
-
# begin_at :datetime
-
# end_at :datetime
-
# exclude_begin :boolean default(TRUE)
-
# exclude_end :boolean default(TRUE)
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
# addressable_id :integer
-
#
-
1
module BxBlockFedexIntegration
-
1
class ArrivalWindow < BxBlockFedexIntegration::ApplicationRecord
-
1
self.table_name = :arrival_windows
-
-
1
END_AT_DAYS = 10.freeze
-
-
1
belongs_to :addressable, class_name: "BxBlockFedexIntegration::Addressable"
-
-
1
after_initialize :set_end_at
-
-
1
private
-
-
1
def set_end_at
-
1
self.end_at ||= begin_at + END_AT_DAYS.days if begin_at.present?
-
end
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: cod_values
-
#
-
# id :bigint not null, primary key
-
# shipment_id :bigint not null
-
# amount :float
-
# currency :string default("RS")
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
#
-
1
module BxBlockFedexIntegration
-
1
class CodValue < BxBlockFedexIntegration::ApplicationRecord
-
1
self.table_name = :cod_values
-
-
1
belongs_to :shipment, class_name: "BxBlockFedexIntegration::Shipment"
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: coordinates
-
#
-
# id :bigint not null, primary key
-
# latitude :string
-
# longitude :string
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
# addressable_id :integer
-
#
-
1
module BxBlockFedexIntegration
-
1
class Coordinate < BxBlockFedexIntegration::ApplicationRecord
-
1
self.table_name = :coordinates
-
-
1
belongs_to :addressable, class_name: "BxBlockFedexIntegration::Addressable"
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: create_shipments
-
#
-
# id :bigint not null, primary key
-
# auto_assign_drivers :boolean default(FALSE)
-
# requested_by :string
-
# shipper_id :string
-
# waybill :string
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
#
-
1
module BxBlockFedexIntegration
-
1
class CreateShipment < BxBlockFedexIntegration::ApplicationRecord
-
1
self.table_name = :create_shipments
-
-
1
has_many :shipments, class_name: "BxBlockFedexIntegration::Shipment", dependent: :destroy
-
-
1
accepts_nested_attributes_for :shipments
-
-
1
after_initialize :set_default_values
-
-
1
private
-
-
1
def set_default_values
-
2
self.requested_by = ["development","test"].include?(Rails.env) ?
-
'Profile_67ff1b39-37f0-4f6c-aac7-71cf844b331a' : ENV['_525K_PROFILE_ID']
-
2
self.shipper_id = ["development","test"].include?(Rails.env) ?
-
'Profile_67ff1b39-37f0-4f6c-aac7-71cf844b331a' : ENV['_525K_PROFILE_ID']
-
end
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: addressables
-
#
-
# id :bigint not null, primary key
-
# shipment_id :bigint not null
-
# address :text
-
# address2 :text
-
# city :string
-
# country :string
-
# email :string
-
# name :string
-
# phone :string
-
# instructions :text
-
# type :string
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
#
-
module BxBlockFedexIntegration
-
class Delivery < Addressable
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: dimensions
-
#
-
# id :bigint not null, primary key
-
# item_id :bigint not null
-
# height :float
-
# length :float
-
# width :float
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
#
-
1
module BxBlockFedexIntegration
-
1
class Dimension < BxBlockFedexIntegration::ApplicationRecord
-
1
self.table_name = :dimensions
-
-
1
belongs_to :item, class_name: "BxBlockFedexIntegration::Item"
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: items
-
#
-
# id :bigint not null, primary key
-
# shipment_id :bigint not null
-
# ref_id :string
-
# weight :float
-
# quantity :integer
-
# stackable :boolean default(TRUE)
-
# item_type :integer default("PALLET")
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
#
-
1
module BxBlockFedexIntegration
-
1
class Item < BxBlockFedexIntegration::ApplicationRecord
-
1
self.table_name = :items
-
-
1
belongs_to :shipment, class_name: "BxBlockFedexIntegration:Shipment"
-
1
has_one :dimension, class_name: "BxBlockFedexIntegration::Dimension", dependent: :destroy
-
-
1
enum item_type: %w(PALLET BOX OTHER)
-
-
1
accepts_nested_attributes_for :dimension
-
-
1
after_initialize :set_ref_id
-
-
1
private
-
-
1
def set_ref_id
-
2
self.ref_id = loop do
-
2
random_id = "item-#{SecureRandom.hex(10)}"
-
2
break random_id unless Item.exists?(ref_id: random_id)
-
end
-
end
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: addressables
-
#
-
# id :bigint not null, primary key
-
# shipment_id :bigint not null
-
# address :text
-
# address2 :text
-
# city :string
-
# country :string
-
# email :string
-
# name :string
-
# phone :string
-
# instructions :text
-
# type :string
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
#
-
module BxBlockFedexIntegration
-
class Pickup < Addressable
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: shipments
-
#
-
# id :bigint not null, primary key
-
# create_shipment_id :bigint not null
-
# ref_id :string
-
# full_truck :boolean default(FALSE)
-
# load_description :text
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
#
-
1
module BxBlockFedexIntegration
-
1
class Shipment < BxBlockFedexIntegration::ApplicationRecord
-
1
self.table_name = :shipments
-
-
1
belongs_to :create_shipment, class_name: "BxBlockFedexIntegration::CreateShipment"
-
1
has_one :cod_value, dependent: :destroy,
-
class_name: "BxBlockFedexIntegration::CodValue"
-
1
has_one :shipment_value,
-
class_name: "BxBlockFedexIntegration::ShipmentValue", dependent: :destroy
-
1
has_one :delivery,
-
class_name: "BxBlockFedexIntegration::Delivery", dependent: :destroy
-
1
has_one :pickup,
-
class_name: "BxBlockFedexIntegration::Pickup", dependent: :destroy
-
1
has_many :items, class_name: "BxBlockFedexIntegration::Item", dependent: :destroy
-
-
1
accepts_nested_attributes_for :cod_value, :shipment_value, :delivery, :pickup, :items
-
-
1
after_initialize :set_ref_id
-
-
1
private
-
-
1
def set_ref_id
-
6
self.ref_id = loop do
-
6
random_id = "shipment-#{SecureRandom.hex(10)}"
-
6
break random_id unless Shipment.exists?(ref_id: random_id)
-
end
-
end
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: shipment_values
-
#
-
# id :bigint not null, primary key
-
# shipment_id :bigint not null
-
# amount :float
-
# currency :string
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
#
-
1
module BxBlockFedexIntegration
-
1
class ShipmentValue < BxBlockFedexIntegration::ApplicationRecord
-
1
self.table_name = :shipment_values
-
-
1
belongs_to :shipment, class_name: "BxBlockFedexIntegration::Shipment"
-
end
-
end
-
module BxBlockForgotPassword
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
module BxBlockGallery
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
module BxBlockGallery
-
class Photo < ApplicationRecord
-
self.table_name = :photos
-
-
# include ActiveStorageSupport::SupportForBase64
-
# has_many_base64_attached :images
-
# has_many_attached :images
-
# belongs_to :book, class_name: 'BxBlockBook::Book'
-
end
-
end
-
1
module BxBlockHelpCentre
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
1
module BxBlockHelpCentre
-
1
class QuestionAnswer < BxBlockHelpCentre::ApplicationRecord
-
1
self.table_name = :question_answers
-
# belongs_to :question_sub_type
-
1
validates :question, presence: { message: "Question required."}
-
end
-
end
-
1
module BxBlockHelpCentre
-
1
class QuestionSubType < BxBlockHelpCentre::ApplicationRecord
-
1
self.table_name = :question_sub_types
-
1
belongs_to :question_type
-
# has_many :question_answers, :dependent => :destroy
-
1
validates :sub_type, presence: { message: "Question sub type required."}
-
end
-
end
-
1
module BxBlockHelpCentre
-
1
class QuestionType < BxBlockHelpCentre::ApplicationRecord
-
1
self.table_name = :question_types
-
1
has_many :question_sub_types, :dependent => :destroy
-
1
has_many :question_answers, through: :question_sub_types
-
1
validates :que_type, presence: { message: "Question type required."}
-
1
validates :que_type, uniqueness: {
-
case_sensitive: false, message: "Question type already exists."
-
}
-
1
accepts_nested_attributes_for :question_sub_types
-
end
-
end
-
module BxBlockInvoicebilling
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
module BxBlockLandingpage3
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
1
module BxBlockLanguageOptions
-
1
class ApplicationMessage < ApplicationRecord
-
1
self.table_name = :application_messages
-
-
1
translates :message, touch: true
-
-
1
validates :name, presence: true, uniqueness: {case_sensitive: false}
-
1
translation_class.validates :message,
-
presence: { message: "EN translation message can't be blank" },
-
if: -> (trans) { trans.locale == :en }
-
-
1
accepts_nested_attributes_for :translations, allow_destroy: true
-
-
1
def self.translation_message(key)
-
application_message = BxBlockLanguageOptions::ApplicationMessage.find_by(name: key)
-
if application_message.present?
-
return application_message.message if application_message.message.present?
-
"Translation not present for key: #{key}, locale: #{Globalize.locale()}"
-
else
-
"Translation not present for key: #{key}"
-
end
-
end
-
-
1
def self.set_message_for(key, locale, message)
-
application_message = BxBlockLanguageOptions::ApplicationMessage.find_by(name: key)
-
if application_message.present?
-
application_message.update!(locale: locale, message: message)
-
else
-
raise "Translation not present for key: #{key}"
-
end
-
end
-
end
-
end
-
module BxBlockLanguageOptions
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
1
module BxBlockLanguageOptions
-
1
class ContentLanguage < ApplicationRecord
-
1
self.table_name = :contents_languages
-
-
1
belongs_to :account, class_name: "AccountBlock::Account"
-
1
belongs_to :language
-
-
end
-
end
-
1
module BxBlockLanguageOptions
-
1
class Language < ApplicationRecord
-
1
self.table_name = :languages
-
-
1
validates :name, :language_code, uniqueness: {case_sensitive: false}, presence: true
-
-
1
scope :content_languages, -> { where("is_content_language is true") }
-
1
scope :app_languages, -> { where("is_app_language is true") }
-
-
1
has_many :contents_languages,
-
class_name: "BxBlockLanguageOptions::ContentLanguage",
-
join_table: "contents_languages", dependent: :destroy
-
1
has_many :accounts,
-
class_name: "AccountBlock::Account",
-
through: :contents_languages, join_table: "contents_languages"
-
-
1
after_commit :update_available_locales
-
-
1
private
-
-
1
def update_available_locales
-
BxBlockLanguageOptions::SetAvailableLocales.call
-
end
-
-
end
-
end
-
1
module BxBlockLike
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
1
module BxBlockLike
-
1
class Like < BxBlockLike::ApplicationRecord
-
1
self.table_name = :likes
-
-
1
belongs_to :likeable, polymorphic: true
-
-
1
after_create :create_notification
-
-
1
private
-
-
1
def create_notification
-
liked_type = likeable_type == 'AccountBlock::Account' ? 'profile' : 'post'
-
account = AccountBlock::Account.find(self.like_by_id)
-
-
BxBlockPushNotifications::PushNotification.create(
-
account_id: self.like_by_id,
-
push_notificable_type: 'AccountBlock::Account',
-
push_notificable_id: likeable.id ,
-
remarks: "#{account.first_name} #{account.last_name} \
-
liked your #{liked_type}"
-
)
-
end
-
end
-
end
-
module BxBlockLocation
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
1
module BxBlockLocation
-
1
class Location < ApplicationRecord
-
1
self.table_name = :locations
-
1
reverse_geocoded_by :latitude, :longitude
-
-
1
belongs_to :van, class_name: 'BxBlockLocation::Van'
-
end
-
end
-
1
module BxBlockLocation
-
1
class Van < AccountBlock::ApplicationRecord
-
1
self.table_name = :vans
-
-
1
has_one :location,
-
class_name: 'BxBlockLocation::Location',
-
dependent: :destroy
-
1
has_one :service_provider,
-
class_name: 'BxBlockLocation::VanMember',
-
dependent: :destroy, foreign_key: 'account_id'
-
1
has_many :assistants,
-
class_name: 'BxBlockLocation::VanMember',
-
dependent: :destroy, foreign_key: 'account_id'
-
1
has_many :van_members, class_name: 'BxBlockLocation::VanMember', dependent: :destroy
-
1
has_many :reviews, as: :reviewable, class_name: 'BxBlockReviews::Review',dependent: :destroy
-
-
1
has_one_attached :main_photo
-
1
has_many_attached :galleries
-
-
1
before_create :offline_van
-
1
after_create :assign_location
-
-
1
accepts_nested_attributes_for :van_members, :service_provider, :assistants
-
-
1
validates :name, presence: true, uniqueness: true
-
-
1
def service_provider
-
BxBlockRolesPermissions::Role.find_by_name('Merchant').accounts.joins(
-
'JOIN van_members ON van_members.account_id = accounts.id'
-
).where(
-
accounts: { van_members: {van_id: self.id} }
-
)
-
end
-
-
1
def available_vans vans
-
available_service_provider = Array.new
-
service_providers_for_vans(vans).each do |service_provider|
-
unless contains_booked_slot_time(service_provider)
-
van = BxBlockLocation::Van.joins(:van_members).where(
-
'van_members.account_id = ?', service_provider.id
-
).first
-
-
available_service_provider << van.location
-
else
-
next
-
end
-
end
-
available_service_provider
-
end
-
-
1
private
-
-
1
def contains_booked_slot_time(service_provider)
-
contain_booked_slot_time = false
-
get_booked_slots(get_availability(service_provider)).each do |booked_slot|
-
if (booked_slot.start_time..booked_slot.end_time).cover?(Time.now) or
-
(booked_slot.start_time..booked_slot.end_time).cover?(Time.now + 1.hours)
-
contain_booked_slot_time = true
-
break
-
end
-
end
-
contain_booked_slot_time
-
end
-
-
1
def get_availability(service_provider)
-
BxBlockAppointmentManagement::Availability.where(
-
service_provider_id: service_provider.id,
-
availability_date: Date.today.strftime('%d/%m/%y')
-
).first
-
end
-
-
1
def get_booked_slots(availability)
-
BxBlockAppointmentManagement::BookedSlot.where(
-
service_provider_id: availability.service_provider.id,
-
booking_date: Date.today.strftime('%d/%m/%y')
-
).map{ |booked_slot| {
-
start_time: booked_slot.start_time.to_time, end_time: booked_slot.end_time.to_time
-
}
-
}
-
end
-
-
1
def service_providers_for_vans(vans)
-
BxBlockRolesPermissions::Role.find_by_name('Merchant').accounts.joins(
-
'JOIN van_members ON van_members.account_id = accounts.id'
-
).joins(
-
'JOIN availabilities ON availabilities.service_provider_id = accounts.id'
-
).where(
-
'availabilities.availability_date = ?', Date.today.strftime('%d/%m/%y')
-
).joins(
-
'JOIN vans on vans.id = van_members.van_id'
-
).where('vans.id = ?', vans.ids)
-
end
-
-
1
def assign_location
-
self.create_location() unless self.location.present?
-
end
-
-
1
def offline_van
-
self.is_offline = true
-
end
-
-
end
-
end
-
1
module BxBlockLocation
-
1
class VanMember < AccountBlock::ApplicationRecord
-
1
self.table_name = :van_members
-
-
1
belongs_to :van, class_name: 'BxBlockLocation::Van'
-
1
belongs_to :account, class_name: 'AccountBlock::Account'
-
end
-
end
-
module BxBlockLogin
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
module BxBlockNotifications
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
1
module BxBlockNotifications
-
1
class Notification < ApplicationRecord
-
1
self.table_name = :notifications
-
1
belongs_to :account , class_name: 'AccountBlock::Account'
-
-
1
validates :headings, :contents, :account_id, presence: true, allow_blank: false
-
end
-
end
-
1
module BxBlockOrderManagement
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: delivery_addresses
-
#
-
# id :bigint not null, primary key
-
# account_id :bigint not null
-
# address :string
-
# name :string
-
# flat_no :string
-
# zip_code :string
-
# phone_number :string
-
# deleted_at :datetime
-
# latitude :float
-
# longitude :float
-
# residential :boolean default(TRUE)
-
# city :string
-
# state_code :string
-
# country_code :string
-
# state :string
-
# country :string
-
# address_line_2 :string
-
# address_type :string default("home")
-
# address_for :string default("shipping")
-
# is_default :boolean default(FALSE)
-
# landmark :string
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
#
-
1
module BxBlockOrderManagement
-
1
class DeliveryAddress < BxBlockOrderManagement::ApplicationRecord
-
1
self.table_name = :delivery_addresses
-
-
1
belongs_to :account, class_name: "AccountBlock::Account", optional: true
-
1
has_many :delivery_address_orders, dependent: :destroy
-
1
has_many :orders, through: :delivery_address_orders
-
-
1
validates :name, :flat_no, :address, :zip_code, :phone_number, presence: true
-
1
validates :phone_number, format: {
-
with: /^(?:\+?\d{1,3}\s*-?)?\(?(?:\d{3})?\)?[- ]?\d{3}[- ]?\d{4}$/,
-
:multiline => true,
-
message: ' is not valid'
-
}
-
1
validates :address_for, presence: true, inclusion: {
-
in: %w(shipping billing billing_and_shipping)
-
}
-
-
1
scope :rest_addresses, -> (address_id){ where.not(id: address_id) }
-
1
scope :billing_and_shipping, -> { where(address_for: "billing_and_shipping") }
-
1
scope :delivery_add, -> { where(address_for: ['shipping','billing_and_shipping']) }
-
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: delivery_address_orders
-
#
-
# id :bigint not null, primary key
-
# order_id :bigint not null
-
# delivery_address_id :bigint not null
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
#
-
1
module BxBlockOrderManagement
-
1
class DeliveryAddressOrder < BxBlockOrderManagement::ApplicationRecord
-
1
self.table_name = :delivery_address_orders
-
-
1
belongs_to :order
-
1
belongs_to :delivery_address
-
-
1
scope :address_ids, -> (ids) { where(delivery_address_id: ids ) }
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: orders
-
#
-
# id :bigint not null, primary key
-
# order_number :string
-
# amount :float
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
# account_id :bigint
-
# coupon_code_id :bigint
-
# delivery_address_id :bigint
-
# sub_total :decimal(, ) default(0.0)
-
# total :decimal(, ) default(0.0)
-
# status :string
-
# applied_discount :decimal(, ) default(0.0)
-
# cancellation_reason :text
-
# order_date :datetime
-
# is_gift :boolean default(FALSE)
-
# placed_at :datetime
-
# confirmed_at :datetime
-
# in_transit_at :datetime
-
# delivered_at :datetime
-
# cancelled_at :datetime
-
# refunded_at :datetime
-
# source :string
-
# shipment_id :string
-
# delivery_charges :string
-
# tracking_url :string
-
# schedule_time :datetime
-
# payment_failed_at :datetime
-
# returned_at :datetime
-
# tax_charges :decimal(, ) default(0.0)
-
# deliver_by :integer
-
# tracking_number :string
-
# is_error :boolean default(FALSE)
-
# delivery_error_message :string
-
# payment_pending_at :datetime
-
# order_status_id :integer
-
# is_group :boolean default(TRUE)
-
# is_availability_checked :boolean default(FALSE)
-
# shipping_charge :decimal(, )
-
# shipping_discount :decimal(, )
-
# shipping_net_amt :decimal(, )
-
# shipping_total :decimal(, )
-
# total_tax :float
-
#
-
1
module BxBlockOrderManagement
-
1
class Order < BxBlockOrderManagement::ApplicationRecord
-
1
self.table_name = :orders
-
-
1
ORDER_NO_FORMAT = '00000000'
-
-
1
belongs_to :account, class_name: "AccountBlock::Account"
-
1
belongs_to :coupon_code, class_name: "BxBlockCouponCg::CouponCode", optional: true
-
-
1
belongs_to :order_status, optional: true
-
-
1
has_one :order_transaction
-
-
1
has_many :order_items, dependent: :destroy
-
1
has_many :catalogues, class_name: "BxBlockCatalogue::Catalogue", through: :order_items
-
1
has_one :address, class_name: "BxBlockAddress::Address"
-
-
1
has_many :order_trackings, class_name: "OrderTracking", as: :parent
-
1
has_many :trackings, through: :order_trackings
-
-
1
has_many :delivery_address_orders
-
1
has_many :delivery_addresses, through: :delivery_address_orders
-
-
-
1
validates :status, presence: true, inclusion: {
-
in: %w(
-
draft
-
in_cart
-
created
-
placed
-
confirmed
-
in_transit
-
delivered
-
cancelled
-
refunded
-
payment_failed
-
returned
-
payment_pending
-
)
-
}
-
-
1
accepts_nested_attributes_for :order_items, allow_destroy: true
-
-
1
enum deliver_by: %i[fedex]
-
-
1
before_save :set_status
-
1
before_create :add_order_number
-
1
after_create :send_order_draft_mail
-
-
1
include AASM
-
1
aasm column: 'status' do
-
1
state :draft, initial: true
-
1
state :created,:placed, :confirmed, :in_transit, :delivered, :cancelled, :refunded,
-
:payment_failed, :returned, :payment_pending
-
-
1
event :draft do
-
1
transitions to: :draft
-
end
-
-
1
event :created do
-
1
transitions to: :created
-
end
-
-
1
event :pending_order do
-
1
transitions from: %i[draft created payment_failed],
-
to: :payment_pending,
-
after: proc { |*_args| update_state_process }
-
end
-
-
1
event :place_order do
-
1
transitions to: :placed, after: proc { |*_args| update_state_process }
-
end
-
-
1
event :confirm_order do
-
1
transitions to: :confirmed, after: proc{|*_args| update_state_process}
-
end
-
-
1
event :to_transit do
-
1
transitions to: :in_transit, after: proc { |*_args| update_state_process }
-
end
-
-
1
event :payment_failed do
-
1
transitions to: :payment_failed, after: proc { |*_args| update_state_process }
-
end
-
-
1
event :deliver_order do
-
1
transitions to: :delivered, after: proc { |*_args| update_state_process }
-
end
-
-
1
event :cancel_order do
-
1
transitions to: :cancelled, after: proc { |*_args| update_state_process }
-
end
-
-
1
event :refund_order do
-
1
transitions to: :refunded, after: proc { |*_args| update_state_process }
-
end
-
-
1
event :return_order do
-
1
transitions to: :returned, after: proc { |*_args| update_state_process }
-
end
-
-
1
OrderStatus.new_statuses.each do |order_status|
-
state order_status.status.to_s.downcase.to_sym
-
end
-
-
end
-
-
EVENTS = %w[
-
1
pending_order!
-
place_order!
-
confirm_order!
-
to_transit!
-
deliver_order!
-
refund_order!
-
cancel_order!
-
payment_failed!
-
return_order!
-
]
-
-
1
def update_state_process
-
StateProcess.new(self, aasm).call
-
end
-
-
1
def send_order_draft_mail
-
93
if sharable_code.nil?
-
2
o = [('a'..'z'), ('A'..'Z'), ('1'..'9')].map(&:to_a).flatten
-
22
sharable_code = (0...10).map { o[rand(o.length)] }.join
-
2
self.update(sharable_code: sharable_code)
-
end
-
93
timer = AccountBlock::DraftMailTimer.last
-
93
half_hour = (Time.now) + (timer&.first_mail_in_minuts || 30).minutes
-
93
after_seven_days = (Time.now) + (timer&.second_mail_in_days || 7).days
-
93
BxBlockOrderManagement::SendDraftOrderMailWorker.perform_at(half_hour, self.id)
-
93
BxBlockOrderManagement::SendDraftOrderMailWorker.perform_at(after_seven_days, self.id)
-
end
-
-
1
def update_additional_page_price(total_page_count, family_member)
-
get_price = BxBlockBook::Price.find_by(cover_type: cover_type)
-
price_per_page = BxBlockBook::AdditionalPricePerPage.last
-
delivery_charges = BxBlockBook::DeliveryCharge.first.charge
-
-
if family_member
-
calculate_pricing(get_price, price_per_page, delivery_charges, total_page_count, 2)
-
else
-
calculate_pricing(get_price, price_per_page, delivery_charges, total_page_count, 1)
-
end
-
end
-
-
1
def set_status
-
# check_holds
-
127
if (OrderStatus::USER_STATUSES.include? self.status) && !(order_status_id_changed?)
-
1
order_status = OrderStatus.find_or_create_by(status: self.status) if self.status.present?
-
1
self.order_status_id = order_status.id unless self.order_status_id == order_status.id
-
end
-
127
if (order_items.pluck(:order_status_id).uniq != [order_status_id]) && (is_group?)
-
127
self.order_items&.update(order_status_id: order_status_id)
-
end
-
end
-
-
1
def total_price
-
(order_items.sum(:total_price) - applied_discount)&.round(2)
-
end
-
-
1
def total_after_shipping_charge
-
# applied_shipping_charge = ShippingCharge.last
-
applied_shipping_charge = { below: 500.0, charge: 50.0 }
-
if applied_shipping_charge.present?
-
charge = applied_shipping_charge[:charge]
-
self.shipping_charge = charge
-
unless self.total <= applied_shipping_charge[:below]
-
self.shipping_discount = charge
-
else
-
self.shipping_discount = 0.0
-
end
-
else
-
self.shipping_charge = 0.0
-
self.shipping_discount = 0.0
-
end
-
self.shipping_total = self.shipping_charge - self.shipping_discount
-
self.shipping_net_amt = self.shipping_charge - self.shipping_discount
-
self.total = self.total + self.shipping_total
-
end
-
-
1
def total_after_tax_charge
-
# applied_tax = Tax.last
-
applied_tax = { tax_percentage: 18 }
-
if applied_tax.present?
-
tax_charge = ((self.total.to_f * applied_tax[:tax_percentage].to_f)/100).to_f.round(2)
-
self.total_tax = tax_charge
-
self.total = self.total.round(2) + self.total_tax
-
end
-
end
-
-
1
def sub_total_price
-
order_items.sum(:total_price)&.round(2)
-
end
-
-
1
def full_order_cancelled?
-
self.order_items.cancelled.count == self.order_items.count
-
end
-
-
1
def add_order_number
-
93
self.order_number = 'OD' + Order.next_order_number
-
end
-
-
1
def self.next_order_number
-
93
return Order::ORDER_NO_FORMAT.succ if Order.count.nil?
-
93
(Order.count&.positive? ?
-
Order.last&.order_number&.split('OD')[1] : Order::ORDER_NO_FORMAT).succ
-
end
-
-
1
def update_shipment_details(json_response)
-
if json_response['status'].to_s.downcase == 'NEW'
-
order_status_id = OrderStatus.find_by(status:"confirmed").id
-
end
-
puts "======================= update shipment details ================"
-
self.update(logistics_ship_rocket_enabled: true, ship_rocket_order_id: json_response['order_id'], ship_rocket_shipment_id: json_response['shipment_id'], ship_rocket_status: json_response['status'].to_s.downcase, ship_rocket_status_code: json_response['status_code'], ship_rocket_onboarding_completed_now: json_response['onboarding_completed_now'], ship_rocket_awb_code: json_response['awb_code'], ship_rocket_courier_company_id: json_response['courier_company_id'], ship_rocket_courier_name: json_response['courier_name'], order_status_id: order_status_id.present? ? order_status_id : self.order_status_id )
-
end
-
-
1
def calculate_pricing(get_price, price_per_page, delivery_charges, total_page_count, multiply)
-
base_price = get_price.price * multiply
-
delivery_charges = delivery_charges * multiply
-
if total_page_count > get_price.min_limit
-
extra_pages = total_page_count - get_price.min_limit
-
additional_price = (extra_pages * price_per_page.additional_price) * multiply
-
total = additional_price + base_price
-
else
-
extra_pages = nil
-
additional_price = nil
-
total = base_price.round(2)
-
end
-
-
delivery_and_tax_charges = (base_price.to_i + delivery_charges.to_i + additional_price.to_i - self.applied_discount.to_i).round(2)
-
tax = (delivery_and_tax_charges *(18.0 / 100)).round(2)
-
sub_total_amount = (base_price.to_i + delivery_charges.to_i + additional_price.to_i + tax.to_f).round(2)
-
-
self.update(base_price: base_price, total: total, additional_price: additional_price, additional_pages: extra_pages, no_of_pages: total_page_count, sub_total: sub_total_amount, tax_charges: tax, amount: sub_total_amount)
-
-
end
-
1
def test(image)
-
"data:image/jpeg\;base64\,\ #{Base64.encode64(AccountBlock::DocxDownloadService.new(image).doc)}".delete "\n"
-
end
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: order_items
-
#
-
# id :bigint not null, primary key
-
# order_id :bigint not null
-
# quantity :integer
-
# unit_price :decimal(, )
-
# total_price :decimal(, )
-
# old_unit_price :decimal(, )
-
# status :string
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
# catalogue_id :bigint not null
-
# catalogue_variant_id :bigint not null
-
# order_status_id :integer
-
# placed_at :datetime
-
# confirmed_at :datetime
-
# in_transit_at :datetime
-
# delivered_at :datetime
-
# cancelled_at :datetime
-
# refunded_at :datetime
-
# manage_placed_status :boolean default(FALSE)
-
# manage_cancelled_status :boolean default(FALSE)
-
#
-
1
module BxBlockOrderManagement
-
1
class OrderItem < BxBlockOrderManagement::ApplicationRecord
-
1
self.table_name = :order_items
-
-
1
belongs_to :order
-
1
belongs_to :catalogue, class_name: "BxBlockCatalogue::Catalogue"
-
1
belongs_to :catalogue_variant,
-
class_name: "BxBlockCatalogue::CatalogueVariant", optional: true
-
-
1
belongs_to :order_status, optional: true
-
-
1
has_many :order_trackings, class_name: "OrderTracking", as: :parent
-
1
has_many :trackings, through: :order_trackings
-
-
1
scope :get_records, -> (ids){ where(order_id: ids) }
-
-
1
include AASM
-
1
aasm column: 'status' do
-
1
state :in_cart, initial: true
-
1
state :created,:placed, :confirmed, :in_transit, :delivered, :cancelled,
-
:refunded, :payment_failed, :returned, :payment_pending
-
-
1
event :in_cart do
-
1
transitions to: :in_cart
-
end
-
-
1
event :created do
-
1
transitions to: :created
-
end
-
-
1
event :pending_order do
-
1
transitions from: %i[in_cart created payment_failed],
-
to: :payment_pending,
-
after: proc { |*_args| update_state_process }
-
end
-
-
1
event :place_order do
-
1
transitions to: :placed,
-
after: proc { |*_args| update_state_process }
-
end
-
-
1
event :confirm_order do
-
1
transitions to: :confirmed,
-
after: proc{|*_args| update_state_process }
-
end
-
-
1
event :to_transit do
-
1
transitions to: :in_transit,
-
after: proc { |*_args| update_state_process }
-
end
-
-
1
event :payment_failed do
-
1
transitions to: :payment_failed,
-
after: proc { |*_args| update_state_process }
-
end
-
-
1
event :deliver_order do
-
1
transitions to: :delivered,
-
after: proc { |*_args| update_state_process }
-
end
-
-
1
event :cancel_order do
-
1
transitions to: :cancelled,
-
after: proc { |*_args| update_state_process }
-
end
-
-
1
event :refund_order do
-
1
transitions to: :refunded,
-
after: proc { |*_args| update_state_process }
-
end
-
-
1
event :return_order do
-
1
transitions to: :returned,
-
after: proc { |*_args| update_state_process }
-
end
-
-
end
-
-
# before_save :update_prices
-
1
before_save :set_item_status, if: :order_status_id_changed?
-
1
after_save :update_product_stock, if: :order_status_id_changed?
-
-
1
def update_prices
-
# if from_catalogue_warehouse
-
self.unit_price = price
-
self.total_price = order_item_total
-
# end
-
end
-
-
1
def set_item_status
-
if (self.status.present?) && !(self.order_status.present?)
-
self.order_status_id = OrderStatus.find_or_create_by(
-
status: self.status
-
).id
-
end
-
event_name = order_status&.event_name
-
self.send("#{event_name}!") unless order_status&.status == status
-
end
-
-
1
def is_order_paced
-
!self.manage_placed_status && self.order_status.present? &&
-
self.order_status.status == "placed"
-
end
-
-
1
def is_order_cancelled
-
!self.manage_cancelled_status && self.order_status.present? &&
-
self.order_status.status == "cancelled"
-
end
-
-
1
def update_product_stock
-
product = self.catalogue_variant.present? ? self.catalogue_variant : self.catalogue
-
if is_order_paced
-
stock_qty = (product.stock_qty.to_i - self.quantity)
-
block_qty = product.block_qty.to_i - self.quantity.to_i
-
product.update!(stock_qty: stock_qty, block_qty: block_qty)
-
if product.class.name == "CatalogueVariant"
-
product.catalogue.update(
-
stock_qty: product.catalogue.stock_qty - self.quantity,
-
block_qty: product.catalogue.block_qty.to_i - self.quantity.to_i
-
)
-
end
-
self.update_attributes(manage_placed_status: true)
-
elsif is_order_cancelled
-
# block_qty = product.block_qty.to_i - self.quantity.to_i
-
product.update_attributes(stock_qty: product.stock_qty + self.quantity )
-
if product.class.name == "CatalogueVariant"
-
product.catalogue.update(stock_qty: product.catalogue.stock_qty + self.quantity)
-
end
-
self.update_attributes(manage_cancelled_status: true)
-
end
-
end
-
-
1
def from_catalogue_warehouse
-
self.catalogue_variant.present? ? self.catalogue_variant : self.catalogue
-
end
-
-
1
def price
-
if self.catalogue_variant.present?
-
catalogue_variant&.on_sale? ?
-
catalogue_variant&.sale_price : catalogue_variant&.actual_price
-
else
-
catalogue&.on_sale? ? catalogue&.sale_price : catalogue&.price
-
end
-
end
-
-
1
def order_item_total
-
(quantity * price)
-
end
-
-
1
def update_state_process
-
StateProcess.new(self, aasm).call
-
end
-
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: order_statuses
-
#
-
# id :bigint not null, primary key
-
# name :string
-
# status :string
-
# active :boolean default(TRUE)
-
# event_name :string
-
# message :string
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
#
-
1
module BxBlockOrderManagement
-
1
class OrderStatus < BxBlockOrderManagement::ApplicationRecord
-
1
self.table_name = :order_statuses
-
-
1
has_many :orders
-
1
has_many :order_items
-
-
1
validates_uniqueness_of :status
-
-
1
before_save :add_status
-
-
1
scope :new_statuses, ->{
-
1
where.not(status: [
-
:in_cart,
-
:created,
-
:placed,
-
:confirmed,
-
:in_transit,
-
:delivered,
-
:cancelled,
-
:refunded,
-
:payment_failed,
-
:returned,
-
:payment_pending]
-
)
-
}
-
-
USER_STATUSES = %w[
-
1
in_cart
-
created
-
placed
-
payment_failed
-
payment_pending
-
]
-
-
CUSTOM_STATUSES = %w[
-
1
in_cart
-
created
-
placed
-
confirmed
-
in_transit
-
delivered
-
cancelled
-
refunded
-
payment_failed
-
returned
-
payment_pending
-
]
-
-
1
private
-
-
1
def add_status
-
3
unless self.status.present?
-
1
self.status = self.name.to_s.downcase.parameterize.underscore
-
end
-
3
unless self.event_name.present?
-
3
self.event_name = self.name.to_s.downcase.parameterize.underscore
-
end
-
end
-
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: order_trackings
-
#
-
# id :bigint not null, primary key
-
# parent_type :string
-
# parent_id :bigint
-
# tracking_id :integer
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
#
-
1
module BxBlockOrderManagement
-
1
class OrderTracking < BxBlockOrderManagement::ApplicationRecord
-
1
self.table_name = :order_trackings
-
-
1
belongs_to :parent, polymorphic: true
-
1
belongs_to :tracking
-
-
1
scope :parent_orders, -> { where(parent_type: 'Order') }
-
1
scope :parent_order_items, -> { where(parent_type: 'OrderItem') }
-
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: order_transactions
-
#
-
# id :bigint not null, primary key
-
# account_id :bigint not null
-
# order_id :bigint not null
-
# charge_id :string
-
# amount :integer
-
# currency :string
-
# charge_status :string
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
#
-
1
module BxBlockOrderManagement
-
1
class OrderTransaction < BxBlockOrderManagement::ApplicationRecord
-
1
self.table_name = :order_transactions
-
-
1
belongs_to :account, class_name: "AccountBlock::Account"
-
1
belongs_to :order
-
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: trackings
-
#
-
# id :bigint not null, primary key
-
# status :string
-
# tracking_number :string
-
# date :datetime
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
#
-
1
module BxBlockOrderManagement
-
1
class Tracking < BxBlockOrderManagement::ApplicationRecord
-
1
self.table_name = :trackings
-
-
1
has_many :order_trackings, dependent: :destroy
-
-
1
has_many :orders, through: :order_trackings, source: :parent, source_type: 'Order'
-
1
has_many :order_items, through: :order_trackings, source: :parent, source_type: 'OrderItem'
-
-
-
1
TRACKING_NO_FORMAT = '00000000'
-
-
1
before_create :add_tracking_number
-
-
1
def add_tracking_number
-
self.tracking_number = 'TR' + next_tracking_number
-
end
-
-
1
def next_tracking_number
-
return Tracking::TRACKING_NO_FORMAT.succ if Tracking.count.nil?
-
(Tracking.count&.positive? ?
-
Tracking.last&.tracking_number&.split('TR')[1] : Tracking::TRACKING_NO_FORMAT).succ
-
end
-
-
end
-
end
-
1
module BxBlockOrdersummary
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
1
module BxBlockOrdersummary
-
1
class OrderSummary < BxBlockOrdersummary::ApplicationRecord
-
1
self.table_name = :order_summaries
-
-
1
belongs_to :order, class_name: "BxBlockOrderManagement::Order"
-
end
-
end
-
1
module BxBlockPaymentAdmin
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
1
module BxBlockPaymentAdmin
-
1
class PaymentAdmin < BxBlockPaymentAdmin::ApplicationRecord
-
1
self.table_name = :payment_admins
-
1
belongs_to :current_user, class_name: 'AccountBlock::Account'
-
1
belongs_to :account, class_name: 'AccountBlock::Account'
-
1
enum payment_method: [:paypal, :apple_pay]
-
end
-
end
-
# frozen_string_literal: true
-
-
1
module BxBlockPlan
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
# frozen_string_literal: true
-
-
1
module BxBlockPlan
-
1
class Plan < BxBlockPlan::ApplicationRecord
-
1
self.table_name = :plans
-
1
enum duration: ['3 Months', '6 Months', '1 Year']
-
-
1
validate :create_only_three, on: :create
-
-
1
private
-
-
1
def create_only_three
-
1
errors.add(:base, "You can't create more than three plans.") if BxBlockPlan::Plan.count > 2
-
end
-
end
-
end
-
1
module BxBlockPosts
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
1
module BxBlockPosts
-
1
class Post < BxBlockPosts::ApplicationRecord
-
1
self.table_name = :posts
-
-
# include BxBlockPosts::Validators
-
# include Validators
-
-
1
IMAGE_CONTENT_TYPES = %w(image/jpg image/jpeg image/png)
-
-
1
has_many_attached :images, dependent: :destroy
-
-
1
belongs_to :category,
-
class_name: 'BxBlockCategories::Category'
-
-
1
belongs_to :sub_category,
-
class_name: 'BxBlockCategories::SubCategory',
-
foreign_key: :sub_category_id, optional: true
-
-
1
belongs_to :account, class_name: 'AccountBlock::Account'
-
1
has_many_attached :media, dependent: :destroy
-
-
1
validates_presence_of :body
-
1
validates :media, blob: {
-
content_type: IMAGE_CONTENT_TYPES,
-
size_range: 1..3.megabytes
-
}
-
-
1
def media_url
-
media_arr = Array.new
-
media.each do |m|
-
media_hash = Hash.new
-
media_hash['url'] = m.service_url(expires_in: Rails.application.config.active_storage.service_urls_expire_in)
-
media_hash['content_type'] = m.content_type
-
media_arr << media_hash
-
end
-
media_arr
-
end
-
-
1
def upload_post_images(images_params)
-
images_to_attach = []
-
-
images_params.each do |image_data|
-
if image_data[:data]
-
decoded_data = Base64.decode64(image_data[:data].split(',')[1])
-
images_to_attach.push(
-
io: StringIO.new(decoded_data),
-
content_type: image_data[:content_type],
-
filename: image_data[:filename]
-
)
-
end
-
end
-
self.images.attach(images_to_attach) if images_to_attach.size.positive?
-
end
-
end
-
end
-
1
module BxBlockPrivacySettings
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
1
module BxBlockPrivacySettings
-
1
class PrivacyPolicy < ApplicationRecord
-
1
self.table_name = :privacy_policies
-
1
validate :create_only_one, on: :create
-
-
1
validates :description, presence: true
-
-
1
private
-
-
1
def create_only_one
-
errors.add(:base, "There can only be one privacy policy") if PrivacyPolicy.count > 0
-
end
-
end
-
end
-
1
module BxBlockPrivacySettings
-
1
class PrivacySetting < BxBlockPrivacySettings::ApplicationRecord
-
1
self.table_name = :privacy_settings
-
1
include Wisper::Publisher
-
-
1
belongs_to :account, class_name: 'AccountBlock::Account'
-
end
-
end
-
1
module BxBlockProfile
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
1
module BxBlockProfile
-
1
class Associated < BxBlockProfile::ApplicationRecord
-
1
self.table_name = :associateds
-
1
has_many :associated_projects, class_name: "BxBlockProfile::AssociatedProject"
-
end
-
end
-
module BxBlockProfile
-
class AssociatedProject < BxBlockProfile::ApplicationRecord
-
self.table_name = :associated_projects
-
belongs_to :project, class_name: "BxBlockProfile::Project"
-
belongs_to :associated, class_name: "BxBlockProfile::Associated"
-
end
-
end
-
1
module BxBlockProfile
-
1
class Award < BxBlockProfile::ApplicationRecord
-
1
self.table_name = :awards
-
1
belongs_to :profile, class_name: "BxBlockProfile::Profile"
-
1
validates :profile_id, presence: true
-
end
-
end
-
1
module BxBlockProfile
-
1
class CareerExperience < BxBlockProfile::ApplicationRecord
-
1
self.table_name = :career_experiences
-
1
belongs_to :profile, class_name: "BxBlockProfile::Profile"
-
1
has_many :career_experience_industrys, class_name: "BxBlockProfile::CareerExperienceIndustry"
-
1
has_many :career_experience_employment_types, class_name: "BxBlockProfile::CareerExperienceEmploymentType"
-
1
has_many :career_experience_system_experiences, class_name: "BxBlockProfile::CareerExperienceSystemExperience"
-
end
-
end
-
1
module BxBlockProfile
-
1
class CareerExperienceEmploymentType < BxBlockProfile::ApplicationRecord
-
1
self.table_name = :career_experience_employment_types
-
1
belongs_to :career_experience, class_name: "BxBlockProfile::CareerExperience"
-
1
belongs_to :employment_type, class_name: "BxBlockProfile::EmploymentType"
-
end
-
end
-
1
module BxBlockProfile
-
1
class CareerExperienceIndustry < BxBlockProfile::ApplicationRecord
-
1
self.table_name = :career_experience_industry
-
1
belongs_to :career_experience, class_name: "BxBlockProfile::CareerExperience"
-
1
belongs_to :industry, class_name: "BxBlockProfile::Industry"
-
end
-
end
-
module BxBlockProfile
-
class CareerExperienceSystemExperience < BxBlockProfile::ApplicationRecord
-
self.table_name = :career_experience_system_experiences
-
belongs_to :career_experience, class_name: "BxBlockProfile::CareerExperience"
-
belongs_to :system_experience, class_name: "BxBlockProfile::SystemExperience"
-
end
-
end
-
1
module BxBlockProfile
-
1
class Course < BxBlockProfile::ApplicationRecord
-
1
self.table_name = :courses
-
1
belongs_to :profile, class_name: "BxBlockProfile::Profile"
-
1
validates :profile_id, presence: true
-
end
-
end
-
1
module BxBlockProfile
-
1
class CurrentAnnualSalary < BxBlockProfile::ApplicationRecord
-
1
self.table_name = :current_annual_salaries
-
1
has_many :current_annual_salary_current_status, class_name: "BxBlockProfile::CurrentAnnualSalaryCurrentStatus"
-
end
-
end
-
1
module BxBlockProfile
-
1
class CurrentAnnualSalaryCurrentStatus < BxBlockProfile::ApplicationRecord
-
1
self.table_name = :current_annual_salary_current_status
-
1
belongs_to :current_status, class_name: "BxBlockProfile::CurrentStatus"
-
1
belongs_to :current_annual_salary, class_name: "BxBlockProfile::CurrentAnnualSalary"
-
end
-
end
-
1
module BxBlockProfile
-
1
class CurrentStatus < BxBlockProfile::ApplicationRecord
-
1
self.table_name = :current_status
-
1
belongs_to :profile, class_name: "BxBlockProfile::Profile"
-
1
has_many :current_status_industrys, class_name: "BxBlockProfile::CurrentStatusIndustry"
-
1
has_many :current_status_employment_types, class_name: "BxBlockProfile::CurrentStatusEmploymentType"
-
1
has_many :current_annual_salary_current_status, class_name: "BxBlockProfile::CurrentAnnualSalaryCurrentStatus"
-
end
-
end
-
1
module BxBlockProfile
-
1
class CurrentStatusEmploymentType < BxBlockProfile::ApplicationRecord
-
1
self.table_name = :current_status_employment_types
-
1
belongs_to :current_status, class_name: "BxBlockProfile::CurrentStatus"
-
1
belongs_to :employment_type, class_name: "BxBlockProfile::EmploymentType"
-
end
-
end
-
1
module BxBlockProfile
-
1
class CurrentStatusIndustry < BxBlockProfile::ApplicationRecord
-
1
self.table_name = :current_status_industries
-
1
belongs_to :current_status, class_name: "BxBlockProfile::CurrentStatus"
-
1
belongs_to :industry, class_name: "BxBlockProfile::Industry"
-
end
-
end
-
1
module BxBlockProfile
-
1
class Degree < BxBlockProfile::ApplicationRecord
-
1
self.table_name = :degrees
-
1
has_many :degree_educational_qualifications,
-
class_name: "BxBlockProfile::DegreeEducationalQualification"
-
end
-
end
-
1
module BxBlockProfile
-
1
class DegreeEducationalQualification < BxBlockProfile::ApplicationRecord
-
1
self.table_name = :degree_educational_qualifications
-
1
belongs_to :degree, class_name: "BxBlockProfile::Degree"
-
1
belongs_to :educational_qualification, class_name: "BxBlockProfile::EducationalQualification"
-
end
-
end
-
1
module BxBlockProfile
-
1
class EducationalQualification < BxBlockProfile::ApplicationRecord
-
1
self.table_name = :educational_qualifications
-
1
belongs_to :profile, class_name: "BxBlockProfile::Profile"
-
1
has_many :degree_educational_qualifications, class_name: "BxBlockProfile::DegreeEducationalQualification"
-
1
has_many :educational_qualification_field_studys, class_name: "BxBlockProfile::EducationalQualificationFieldStudy"
-
end
-
end
-
1
module BxBlockProfile
-
1
class EducationalQualificationFieldStudy < BxBlockProfile::ApplicationRecord
-
1
self.table_name = :educational_qualification_field_study
-
1
belongs_to :field_study, class_name: "BxBlockProfile::FieldStudy"
-
1
belongs_to :educational_qualification, class_name: "BxBlockProfile::EducationalQualification"
-
end
-
end
-
1
module BxBlockProfile
-
1
class EmploymentType < BxBlockProfile::ApplicationRecord
-
1
self.table_name = :employment_types
-
1
has_many :current_status_employment_types, class_name: "BxBlockProfile::CurrentStatusEmploymentType"
-
1
has_many :career_experience_employment_types, class_name: "BxBlockProfile::CareerExperienceEmploymentType"
-
end
-
end
-
1
module BxBlockProfile
-
1
class FieldStudy < BxBlockProfile::ApplicationRecord
-
1
self.table_name = :field_study
-
1
has_many :educational_qualification_field_studys, class_name: "BxBlockProfile::EducationalQualificationFieldStudy"
-
end
-
end
-
1
module BxBlockProfile
-
1
class Hobby < BxBlockProfile::ApplicationRecord
-
1
self.table_name = :hobbies_and_interests
-
1
belongs_to :profile, class_name: "BxBlockProfile::Profile"
-
1
validates :profile_id, presence: true
-
end
-
end
-
1
module BxBlockProfile
-
1
class Industry < BxBlockProfile::ApplicationRecord
-
1
self.table_name = :industries
-
1
has_many :current_status_industrys, class_name: "BxBlockProfile::CurrentStatusIndustry"
-
1
has_many :career_experience_industrys, class_name: "BxBlockProfile::CareerExperienceIndustry"
-
end
-
end
-
1
module BxBlockProfile
-
1
class Language < BxBlockProfile::ApplicationRecord
-
1
self.table_name = :languages
-
1
belongs_to :profile, class_name: "BxBlockProfile::Profile"
-
1
validates :profile_id, presence: true
-
end
-
end
-
1
module BxBlockProfile
-
1
class Profile < BxBlockProfile::ApplicationRecord
-
1
self.table_name = :profiles
-
1
has_one_attached :photo
-
1
belongs_to :account, class_name: "AccountBlock::Account"
-
1
has_one :current_status, dependent: :destroy, class_name: "BxBlockProfile::CurrentStatus"
-
1
accepts_nested_attributes_for :current_status, allow_destroy: true
-
1
has_one :publication_patent,dependent: :destroy, class_name: "BxBlockProfile::PublicationPatent"
-
1
accepts_nested_attributes_for :publication_patent, allow_destroy: true
-
1
has_many :awards, dependent: :destroy, class_name: "BxBlockProfile::Award"
-
1
accepts_nested_attributes_for :awards, allow_destroy: true
-
1
has_many :hobbies, dependent: :destroy, class_name: "BxBlockProfile::Hobby"
-
1
accepts_nested_attributes_for :hobbies, allow_destroy: true
-
1
has_many :courses, dependent: :destroy, class_name: "BxBlockProfile::Course"
-
1
accepts_nested_attributes_for :courses, allow_destroy: true
-
1
has_many :test_score_and_courses,dependent: :destroy, class_name: "BxBlockProfile::TestScoreAndCourse"
-
1
accepts_nested_attributes_for :test_score_and_courses, allow_destroy: true
-
1
has_many :career_experiences,dependent: :destroy, class_name: "BxBlockProfile::CareerExperience"
-
1
accepts_nested_attributes_for :career_experiences, allow_destroy: true
-
1
has_one :video, class_name: "BxBlockVideolibrary::Video"
-
1
has_many :educational_qualifications, dependent: :destroy,class_name: "BxBlockProfile::EducationalQualification"
-
1
accepts_nested_attributes_for :educational_qualifications, allow_destroy: true
-
1
has_many :projects,dependent: :destroy, class_name: "BxBlockProfile::Project"
-
1
accepts_nested_attributes_for :projects, allow_destroy: true
-
1
has_many :languages, class_name: "BxBlockProfile::Language"
-
1
has_many :contacts, class_name: "BxBlockContactsintegration::Contact"
-
1
has_many :jobs, class_name: "BxBlockJobListing::Job"
-
1
has_many :applied_jobs, class_name: "BxBlockJobListing::AppliedJob"
-
1
has_many :follows, class_name: "BxBlockJobListing::Follow"
-
# has_many :company_pages, through: :follows , class_name: "BxBlockJoblisting::CompanyPage"
-
1
has_many :interview_schedules, class_name: "BxBlockCalendar::InterviewSchedule"
-
1
has_and_belongs_to_many :company_pages,
-
class_name: "BxBlockJobListing::CompanyPage",
-
join_table: :profiles_company_pages
-
1
validates :profile_role, presence: true
-
1
enum profile_role: [:jobseeker, :recruiter]
-
1
validate :profile_validation
-
1
private
-
-
1
def profile_validation
-
1
if account && account.profiles.count >= 2
-
errors.add(:profiles, "for an account can not exceed count of 2")
-
end
-
end
-
-
1
def photo_present?
-
errors.add(:photo, :blank) unless photo.attached?
-
end
-
-
end
-
end
-
-
-
1
module BxBlockProfile
-
1
class Project < BxBlockProfile::ApplicationRecord
-
1
self.table_name = :projects
-
1
belongs_to :profile, class_name: "BxBlockProfile::Profile"
-
1
has_many :associated_projects, class_name: "BxBlockProfile::AssociatedProject"
-
end
-
end
-
1
module BxBlockProfile
-
1
class PublicationPatent < BxBlockProfile::ApplicationRecord
-
1
self.table_name = :publication_patents
-
1
belongs_to :profile, class_name: "BxBlockProfile::Profile"
-
end
-
end
-
1
module BxBlockProfile
-
1
class SystemExperience < BxBlockProfile::ApplicationRecord
-
1
self.table_name = :system_experiences
-
1
has_many :career_experience_system_experiences, class_name: "BxBlockProfile::CareerExperienceSystemExperience"
-
end
-
end
-
1
module BxBlockProfile
-
1
class TestScoreAndCourse < BxBlockProfile::ApplicationRecord
-
1
self.table_name = :test_score_and_courses
-
1
belongs_to :profile, class_name: "BxBlockProfile::Profile"
-
1
validates :profile_id, presence: true
-
end
-
end
-
module BxBlockProjecttemplates
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
module BxBlockPushNotifications
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
1
module BxBlockPushNotifications
-
1
class PushNotification < ApplicationRecord
-
1
require 'fcm'
-
1
self.table_name = :push_notifications
-
-
1
belongs_to :push_notificable, polymorphic: true
-
1
belongs_to :account, class_name: "AccountBlock::Account"
-
1
validates :remarks, presence:true
-
1
before_create :send_push_notification
-
-
1
def send_push_notification
-
if push_notificable.activated && push_notificable.device_id &&
-
push_notificable.privacy_setting["#{notify_type}".to_sym]
-
fcm_client = FCM.new(ENV['FCM_SEVER_KEY']) # set your FCM_SERVER_KEY
-
options = { priority: 'high',
-
data: {
-
message: remarks,
-
notify_type: "#{notify_type}",
-
account_id: account_id
-
},
-
notification: {
-
body: remarks,
-
sound: 'default'
-
}
-
}
-
registration_id = push_notificable.device_id
-
# A registration ID looks something like:
-
#“dAlDYuaPXes:APA91bFEipxfcckxglzRo8N1SmQHqC6g8SWFATWBN9orkwgvTM57kmlFOUYZAmZKb4XGGOOL
-
#9wqeYsZHvG7GEgAopVfVupk_gQ2X5Q4Dmf0Cn77nAT6AEJ5jiAQJgJ_LTpC1s64wYBvC”
-
fcm_client.send(registration_id, options)
-
end
-
rescue Exception => e
-
e
-
end
-
end
-
end
-
1
module BxBlockReferrals
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
1
module BxBlockReferrals
-
1
class ReferralLimitSetting < BxBlockReferrals::ApplicationRecord
-
1
self.table_name = :referral_limit_settings
-
end
-
end
-
1
module BxBlockReferrals
-
1
class ReferralUser < ApplicationRecord
-
1
self.table_name = :referral_user
-
-
1
belongs_to :accounts, class_name: 'AccountBlock::Account'
-
-
end
-
end
-
-
module BxBlockRefundmanagement
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
1
module BxBlockRequestManagement
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
1
module BxBlockRequestManagement
-
1
class Request < BxBlockRequestManagement::ApplicationRecord
-
1
self.table_name = :requests
-
-
1
belongs_to :account, class_name: 'AccountBlock::Account'
-
1
belongs_to :sender, foreign_key: :sender_id, class_name: 'AccountBlock::Account'
-
-
1
enum status: %i[Accepted Rejected], _prefix: :status
-
-
1
scope :pending, -> { where(status: nil) }
-
1
scope :accepted, -> { where(status: 'Accepted') }
-
1
scope :rejected, -> { where(status: 'Rejected') }
-
-
1
attr_accessor :mutual_friends
-
-
1
private
-
-
1
def self.mutual_friend(current_account, requests)
-
requests.each do |req|
-
if req.sender_id == current_account.id
-
sender_friends = BxBlockRequestManagement::Request.where(
-
"(sender_id=? or account_id=?) and status=?", req.account_id, req.account_id, 0
-
).pluck(:account_id, :sender_id)
-
sender_friends = sender_friends.flatten - [req.account_id]
-
else
-
sender_friends = BxBlockRequestManagement::Request.where(
-
"(sender_id=? or account_id=?) and status=?", req.sender_id, req.sender_id, 0
-
).pluck(:account_id, :sender_id)
-
sender_friends = sender_friends.flatten - [req.sender_id]
-
end
-
receiver_friends = BxBlockRequestManagement::Request.where(
-
"(sender_id=? or account_id=?) and status=?", current_account.id, current_account.id, 0
-
).pluck(:account_id, :sender_id)
-
receiver_friends = receiver_friends.flatten - [current_account.id]
-
-
mutual_friend_ids = sender_friends & receiver_friends
-
friends = AccountBlock::Account.where(id: mutual_friend_ids)
-
req.mutual_friends = friends || []
-
end
-
end
-
end
-
end
-
1
module BxBlockReviews
-
1
class ApplicationRecord < BuilderBase::ApplicationRecord
-
1
self.abstract_class = true
-
end
-
end
-
1
module BxBlockReviews
-
1
class Review < BxBlockReviews::ApplicationRecord
-
1
self.table_name = :reviews_reviews
-
-
1
belongs_to :account, class_name: 'AccountBlock::Account'
-
1
belongs_to :reviewer, foreign_key: :reviewer_id, class_name: 'AccountBlock::Account'
-
1
validates :account_id,
-
uniqueness: { scope: [:reviewer_id, :anonymous], message: 'already reviewed' },
-
if: :reviewer_id?
-
-
1
validates_presence_of :title, :description
-
end
-
end
-
module BxBlockRolesPermissions
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
1
module BxBlockRolesPermissions
-
1
class Role < ApplicationRecord
-
1
self.table_name = :roles
-
-
1
has_many :accounts, class_name: 'AccountBlock::Account', dependent: :destroy
-
-
1
validates :name, uniqueness: { message: 'Role already present' }
-
end
-
end
-
module BxBlockScreenshoteditor0
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
module BxBlockSettings
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
1
module BxBlockSettings
-
1
class Setting < ApplicationRecord
-
-
1
self.table_name = :settings
-
-
end
-
end
-
module BxBlockShoppingCart
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
1
module BxBlockShoppingCart
-
1
class Order < ApplicationRecord
-
1
include Wisper::Publisher
-
1
self.table_name = :shopping_cart_orders
-
-
1
BUFFER_TIME = 20 #in minute
-
-
#order status are
-
#upcomming = 'scheduled', ongoing = 'on_going', history = 'cancelled or completed
-
-
1
belongs_to :address, class_name: 'BxBlockAddress::Address'
-
1
belongs_to :service_provider,
-
class_name: 'AccountBlock::Account',
-
foreign_key: :service_provider_id
-
1
belongs_to :customer, class_name: 'AccountBlock::Account', foreign_key: :customer_id
-
1
belongs_to :coupon, class_name: 'BxBlockCoupons::Coupon', optional: true
-
1
has_one :booked_slot,
-
class_name: "BxBlockAppointmentManagement::BookedSlot",
-
dependent: :destroy
-
-
1
has_and_belongs_to_many :sub_categories,
-
class_name: 'BxBlockCategories::SubCategory',
-
join_table: :order_services, foreign_key: :shopping_cart_order_id
-
-
1
enum :order_type => { 'instant booking' => 0, 'advance booking' => 1 }
-
-
1
validates_presence_of :booking_date, :slot_start_time, :total_fees, :order_type
-
6
validate :check_service_provide, if: Proc.new {|a|a.new_record?}
-
6
validate :check_major_services, if: Proc.new {|a|a.new_record?}
-
6
validate :check_available_slots, if: Proc.new {|a|a.new_record?}
-
6
validate :check_order_status, if: Proc.new {|a| !a.new_record?}
-
1
validate :instant_booking_slots,
-
5
if: Proc.new { |order| order.order_type == 'instant booking' && order.new_record? }
-
1
validate :advance_booking_slots,
-
5
if: Proc.new { |order| order.order_type == 'advance booking' && order.new_record? }
-
-
1
accepts_nested_attributes_for :sub_categories
-
-
1
before_save :check_coupon_detail
-
1
after_create :occupy_time_slot
-
-
1
scope :todays_order, -> { where(slot_start_time: Date.today.strftime('%d/%m/%y')) }
-
1
scope :completed_order, -> { where(status: 'completed') }
-
-
1
def occupy_time_slot
-
start_time = "#{(Time.parse(self.slot_start_time).strftime("%I:%M %p"))}"
-
end_time = get_order_end_time.strftime("%I:%M %p")
-
BxBlockAppointmentManagement::BookedSlot.create(
-
order_id: self.id,
-
start_time: start_time,
-
end_time: end_time,
-
service_provider_id: self.service_provider_id,
-
booking_date: self.booking_date
-
)
-
end
-
-
1
private
-
-
#check slots for the instant booking
-
1
def instant_booking_slots
-
already_booked_slots = get_booked_slots
-
order_start_time = (Time.parse(self.slot_start_time.to_s))
-
mins = 0
-
self.sub_categories.each do |sub_category|
-
mins += sub_category.service_time.to_i
-
end
-
mins = mins.minute + BUFFER_TIME.minute #BUFFER TIME
-
order_end_time = (Time.parse(self.slot_start_time) + mins)
-
include_booked_time = false
-
already_booked_slots.each do |slot|
-
if (slot[:start_time]..slot[:end_time]).cover?(order_start_time) or
-
(slot[:start_time]..slot[:end_time]).cover?(order_end_time)
-
include_booked_time = true
-
break
-
end
-
end
-
errors.add(:invalid_time, 'Booking Slot not Available') if include_booked_time
-
already_booked_slots
-
end
-
-
#check slots for the advance booking
-
1
def advance_booking_slots
-
return errors.add(
-
:booking_date, 'You can not book service provider for today'
-
) if self.booking_date.today?
-
-
availability = self.service_provider.availabilities.find_by_availability_date(
-
self.booking_date.strftime('%d/%m/%y')
-
)
-
-
return errors.add(
-
:availability,
-
"Service provider is unavailable for #{self.booking_date.strftime('%d/%m/%y')}"
-
) unless availability.present?
-
-
slot_list = availability.slots_list
-
slots_available?(slot_list)
-
end
-
-
#Get all booked slots
-
1
def get_booked_slots
-
BxBlockAppointmentManagement::BookedSlot.where(
-
service_provider_id: self.service_provider.id,
-
booking_date: self.booking_date
-
).map do |booked_slot|
-
{ start_time: booked_slot.start_time.to_time, end_time: booked_slot.end_time.to_time }
-
end
-
end
-
-
1
def check_service_provide
-
5
errors.add(
-
:service_provider, 'Invalid service provider'
-
5
) unless self.service_provider.present? and is_merchant?
-
end
-
-
1
def check_coupon_detail
-
unless self.is_coupon_applied
-
self.coupon_id = nil
-
self.discount = nil
-
end
-
end
-
-
1
def check_order_status
-
errors.add(
-
:invalid_request, 'Your order is finished, you can not update it now'
-
) if self.status_was == 'completed'
-
end
-
-
1
def check_available_slots
-
5
order_date = self.booking_date
-
return errors.add(
-
:slot_start_time, 'Please select any slot to book'
-
5
) unless self.slot_start_time.present?
-
order_start_time = (Time.parse(self.slot_start_time.to_s))
-
order_end_time = get_order_end_time
-
service_provider_availability = BxBlockAppointmentManagement::Availability.find_by(
-
service_provider_id: self.service_provider.id,
-
availability_date: self.booking_date.strftime('%d/%m/%y')
-
)
-
return errors.add(
-
:invalid_request,
-
'Service Provider dose not set their time for the day'
-
) unless service_provider_availability.present?
-
-
return errors.add(
-
:invalid_time, 'Booking Slot not Available'
-
) unless service_provider_availability.present? or (
-
service_provider_availability.start_time..service_provider_availability.end_time
-
).cover?(order_start_time) or (
-
service_provider_availability.start_time..service_provider_availability.end_time
-
).cover?(order_end_time)
-
-
unless check_availability_covers_order(
-
service_provider_availability, order_start_time, order_end_time
-
)
-
return errors.add(:invalid_time, 'Booking Slot not Available')
-
end
-
end
-
-
1
def get_order_end_time
-
mins = 0
-
self.sub_categories.each do |sub_category|
-
mins += sub_category.service_time.to_i
-
end
-
mins = mins.minute + BUFFER_TIME.minute #BUFFER TIME
-
(Time.parse(self.slot_start_time) + mins)
-
end
-
-
1
def check_availability_covers_order(availability, order_start_time, order_end_time)
-
if availability.unavailable_start_time.present? &&
-
availability.unavailable_end_time.present?
-
unavailable_start_time = availability.unavailable_start_time.to_time
-
unavailable_end_time = availability.unavailable_end_time.to_time
-
unavailable_slot = (unavailable_start_time..unavailable_end_time)
-
end
-
-
if availability.unavailable_start_time.present? &&
-
availability.unavailable_end_time.present? and
-
(unavailable_slot.cover?(order_end_time) or unavailable_slot.cover?(order_start_time))
-
return false
-
end
-
-
true
-
end
-
-
# Validation function to check the proper availability for the required slots.
-
1
def slots_available?(availability_slots)
-
availability = self.service_provider.availabilities.find_by(
-
availability_date: self.booking_date.strftime("%d/%m/%y")
-
)
-
-
errors.add(
-
:service_provider, "Service Provider is not available on the order placing date."
-
) and return if availability.blank?
-
-
start_time, end_time = get_start_and_end_time
-
time_slot = availability_slots.detect{
-
|time| (Time.parse(time[:from]) == Time.parse(start_time) && time[:booked_status] == false)
-
}
-
greater_time_slots = []
-
if time_slot.present?
-
needed_time_slots = []
-
if Time.parse(time_slot[:to]) < Time.parse(end_time)
-
availability_slots.each do |time|
-
if Time.parse(time[:from]) > Time.parse(start_time)
-
unless time[:booked_status]
-
if ((Time.parse(time[:from])..Time.parse(time[:to])).cover?(Time.parse(end_time)))
-
greater_time_slots << time
-
end
-
else
-
errors.add(
-
:booking_slot,
-
'Your service timings are greater then available slots. May be next slots is ' \
-
'not available. Please try to book your services on any other slots having its ' \
-
'following slot empty.'
-
)
-
end
-
end
-
end
-
greater_time_slots.push(time_slot)
-
if greater_time_slots.count < 1
-
errors.add(:booking_slot, 'Booking Slot not Available')
-
end
-
end
-
else
-
errors.add(:booking_slot, 'Booking Slot not Available')
-
end
-
end
-
-
-
# Fetching the required slots
-
1
def get_available_time_slots
-
availability = self.service_provider.availabilities.find_by(
-
availability_date: self.booking_date.strftime("%d/%m/%y")
-
)
-
start_time, end_time = get_start_and_end_time
-
time_slot = availability.timeslots.detect{
-
|time| (Time.parse(time[:from]) == Time.parse(start_time) && time[:booked_status] == false)
-
}
-
needed_time_slots = []
-
greater_time_slots = []
-
if Time.parse(time_slot[:to]) < Time.parse(end_time)
-
availability.timeslots.each do |time|
-
if Time.parse(time[:from]) > Time.parse(start_time)
-
unless time[:booked_status]
-
if ((Time.parse(time[:from])..Time.parse(time[:to])).cover?(Time.parse(end_time)))
-
greater_time_slots << time
-
end
-
end
-
end
-
end
-
end
-
greater_time_slots.push(time_slot)
-
greater_time_slots
-
end
-
-
# Updating the booked slots status as true
-
1
def modify_occupied_time_slots(greater_time_slots)
-
availability = self.service_provider.availabilities.find_by(
-
availability_date: self.booking_date.strftime("%d/%m/%y")
-
)
-
availability_time_slots = availability.timeslots
-
modified_time_slots = []
-
-
greater_time_slots.each do |time_slot|
-
availability_time_slots.delete_if {|slot| slot[:sno] == time_slot[:sno]}
-
time_slot[:booked_status] = true
-
end
-
final_time_slots = availability_time_slots + greater_time_slots
-
availability.update_column("timeslots", final_time_slots)
-
end
-
-
1
def get_start_and_end_time
-
start_time = "#{(Time.parse(self.slot_start_time).strftime("%I:%M %p"))}"
-
mins = 0
-
self.sub_categories.each do |sub_category|
-
mins += sub_category.service_time.to_i
-
end
-
mins = mins.minute + BUFFER_TIME.minute #BUFFER TIME
-
end_time = (Time.parse(self.slot_start_time) + mins).strftime("%I:%M %p")
-
[start_time, end_time]
-
end
-
-
#To check major service presence
-
1
def check_major_services
-
5
valid_order = false
-
5
self.sub_categories.each do |a|
-
if a.service_type == 'major'
-
valid_order = true
-
break
-
end
-
end
-
5
valid_order
-
end
-
-
1
def update_slots_detail
-
self.service_provider.availabilities
-
end
-
-
1
def is_merchant?
-
role = BxBlockRolesPermissions::Role.find_by(id: self.service_provider.role_id)
-
return false unless role
-
role.name == 'Merchant'
-
end
-
end
-
end
-
module BxBlockStatisticsreports
-
class ApplicationRecord < BuilderBase::ApplicationRecord
-
self.abstract_class = true
-
end
-
end
-
1
module BxBlockStories
-
1
class Blog < ApplicationRecord
-
1
self.table_name = :bx_block_stories_blogs
-
-
1
has_one_attached :blog_file
-
-
1
validates :title, :description, :status, presence: true
-
1
validates_uniqueness_of :title
-
1
validates_length_of :title, minimum: 1, maximum: 100
-
-
1
enum status: %i[active inactive]
-
1
BLOG_CONTENT_TYPE = ['image/bmp', 'image/svg+xml', 'image/webp', 'image/svg', 'image/tiff', 'image/png', 'image/jpg', 'image/jpeg', 'image']
-
1
after_save :save_blog_url
-
-
1
def save_blog_url
-
if self.present? && self.title.present?
-
url = (self.title.split.size > 1 ? self.title.downcase.split(" ").join("-") : self.title.downcase)
-
self.update_attributes(url: url) if url != self.url
-
end
-
end
-
end
-
end
-
1
module BxBlockStories
-
1
class Story < ApplicationRecord
-
1
self.table_name = :bx_block_stories_stories
-
-
1
STORY_CONTENT_TYPE = ['image/bmp', 'image/svg+xml', 'image/webp', 'image/svg', 'image/tiff', 'image/png', 'image/jpg', 'image/jpeg', 'image']
-
-
1
has_one_attached :story_file
-
1
enum story_type: ['story', 'blog']
-
# validates :story_file, attached: true
-
1
validates :valid_till, presence: true
-
11
validates :description, :link, :title, presence: true, if: -> {self.story_type == "blog"}
-
9
validates_length_of :description, minimum: 1, maximum: 400, if: -> {self.story_type == "blog" || self.description.present?}
-
1
validate :story_file_size_image
-
1
validate :check_valid_date
-
-
1
private
-
-
1
def story_file_size_image
-
7
if story_file&.attachment.present?
-
if BxBlockStories::Story::STORY_CONTENT_TYPE.include?(story_file&.content_type)
-
if story_file.blob.byte_size > 2.megabytes
-
errors[:story_file] << "should be less than 2 MB"
-
end
-
end
-
end
-
end
-
-
1
def check_valid_date
-
7
if self.valid_till.present?
-
6
errors.add(:valid_till, "Please enter a valid date and time") if Time.zone.now > valid_till
-
end
-
end
-
end
-
end
-
1
module AccountBlock
-
1
class AccountSerializer < BuilderBase::BaseSerializer
-
1
attributes *[
-
:activated,
-
:country_code,
-
:email,
-
:first_name,
-
:full_phone_number,
-
:last_name,
-
:phone_number,
-
:type,
-
:created_at,
-
:updated_at,
-
:device_id,
-
:shared_link,
-
:provider,
-
:google_token,
-
:unique_auth_id,
-
:referral_code,
-
:referred_by,
-
:referral_used,
-
]
-
-
1
attribute :addresses do |object|
-
1
address = BxBlockAddress::Address.active.where(addressble_id: object.id)
-
1
unique_data = address.uniq { |h| [h[:pincode], h[:state], h[:city], h[:address]] }.uniq { |h| [h[:pincode], h[:state], h[:city], h[:address]] }
-
1
BxBlockAddress::AddressSerializer.new(unique_data).serializable_hash
-
end
-
-
1
attribute :country_code do |object|
-
1
country_code_for object
-
end
-
-
1
attribute :phone_number do |object|
-
1
phone_number_for object
-
end
-
-
1
class << self
-
1
private
-
-
1
def country_code_for(object)
-
1
return nil unless Phonelib.valid?(object.full_phone_number)
-
1
Phonelib.parse(object.full_phone_number).country_code
-
end
-
-
1
def phone_number_for(object)
-
1
return nil unless Phonelib.valid?(object.full_phone_number)
-
1
Phonelib.parse(object.full_phone_number).raw_national
-
end
-
end
-
end
-
end
-
module AccountBlock
-
class CountryCodeAndFlagSerializer < BuilderBase::BaseSerializer
-
attributes :name, :emoji_flag
-
-
set_id do |object|
-
object.alpha2
-
end
-
-
attribute :country_code do |object|
-
object.nanp_prefix || object.country_code
-
end
-
end
-
end
-
1
module AccountBlock
-
1
class DashboardMediaFileSerializer < BuilderBase::BaseSerializer
-
1
attributes *[
-
:name,
-
:priority,
-
]
-
-
1
attribute :media_file do |object, params|
-
if object.media_file.attached?
-
# Rails.application.routes.default_url_options[:host] + Rails.application.routes.url_helpers.rails_blob_path(object.media_file, only_path: true)
-
ENV['HOST_URL'] + Rails.application.routes.url_helpers.rails_blob_path(object.media_file, only_path: true)
-
end
-
end
-
end
-
end
-
1
module AccountBlock
-
1
class EmailAccountSerializer
-
1
include FastJsonapi::ObjectSerializer
-
-
1
attributes *[
-
:first_name,
-
:last_name,
-
:full_phone_number,
-
:country_code,
-
:phone_number,
-
:email,
-
:activated,
-
:shared_link,
-
:referral_code,
-
:referred_by,
-
:email_verified,
-
:phone_verified
-
]
-
end
-
end
-
1
module AccountBlock
-
1
class ProfileSerializer < BuilderBase::BaseSerializer
-
1
attributes *[
-
:email,
-
:first_name,
-
:last_name,
-
:full_name,
-
:full_phone_number,
-
]
-
-
1
attributes :profile_picture do |object|
-
2
Rails.application.routes.url_helpers.rails_blob_path(object.profile_picture, only_path: true) if object.profile_picture.attached?
-
end
-
end
-
end
-
module AccountBlock
-
class SmsAccountSerializer
-
include FastJsonapi::ObjectSerializer
-
-
attributes *[
-
:first_name,
-
:last_name,
-
:full_phone_number,
-
:country_code,
-
:phone_number,
-
:email,
-
:activated,
-
]
-
end
-
end
-
module AccountBlock
-
class SmsOtpSerializer < BuilderBase::BaseSerializer
-
attributes :full_phone_number, :created_at
-
attributes :pin
-
end
-
end
-
module AccountBlock
-
class SocialAccountSerializer
-
include FastJsonapi::ObjectSerializer
-
-
attributes *[
-
:first_name,
-
:last_name,
-
:full_phone_number,
-
:country_code,
-
:phone_number,
-
:email,
-
:activated,
-
:shared_link,
-
:provider,
-
:google_token,
-
:unique_auth_id,
-
:referral_code,
-
:referred_by
-
]
-
end
-
end
-
module AccountBlock
-
class ValidateAvailableSerializer
-
include FastJsonapi::ObjectSerializer
-
-
attributes :activated
-
-
set_id do |object|
-
object.class.name.underscore
-
end
-
-
attribute :email do |object|
-
object.is_a?(EmailAccount) ? object.email : nil
-
end
-
-
attribute :phone_number do |object|
-
object.is_a?(SmsAccount) ? object.full_phone_number : nil
-
end
-
-
attribute :account_exists do |object|
-
object.id.present? ? true : false
-
end
-
end
-
end
-
1
module BuilderBase
-
1
class BaseSerializer
-
1
include FastJsonapi::ObjectSerializer
-
-
1
class << self
-
1
private
-
-
1
def base_url
-
ENV['BASE_URL'] || 'http://localhost:3000'
-
end
-
end
-
end
-
end
-
1
module BxBlockAddress
-
1
class AddressSerializer < BuilderBase::BaseSerializer
-
1
attributes *[
-
:email_address,
-
:phone_number,
-
:full_name,
-
:pincode,
-
:city,
-
:address,
-
:landmark,
-
:state,
-
:order_id,
-
:created_at,
-
:updated_at
-
]
-
-
1
attribute :shared_address do |object|
-
5
SharedAddressSerializer.new(object.shared_address).serializable_hash
-
end
-
-
1
attribute :order_id do |object|
-
5
object.order_id
-
end
-
end
-
end
-
1
module BxBlockAddress
-
1
class SharedAddressSerializer < BuilderBase::BaseSerializer
-
1
attributes *[
-
:phone_number,
-
:full_name,
-
:pincode,
-
:city,
-
:landmark,
-
:state,
-
:address1
-
]
-
end
-
end
-
module BxBlockAppointmentManagement
-
class ServiceProviderAvailabilitySerializer < BuilderBase::BaseSerializer
-
attributes :id
-
-
attribute :time_slots do |object|
-
slots_for(object)
-
end
-
-
class << self
-
private
-
-
def slots_for availability
-
availability.slots_list
-
end
-
end
-
end
-
end
-
1
module BxBlockBook
-
1
class BookColorSerializer < BuilderBase::BaseSerializer
-
1
include JSONAPI::Serializer
-
1
attributes :id, :book_color, :title_color, :logo_color
-
end
-
end
-
1
module BxBlockBook
-
1
class BookSerializer < BuilderBase::BaseSerializer
-
1
include JSONAPI::Serializer
-
1
attributes :id, :year, :month, :images, :flag, :book_status, :book_title, :month_range, :month_year, :book_color, :title_layout, :total_pages, :cover_type, :paper_type, :spine_title, :title_color, :logo_color, :from_year, :from_month, :to_year, :to_month, :cover_image
-
-
1
attribute :total_pages do |object, params|
-
6
if object.images.attached?
-
object.images.count
-
end
-
end
-
-
1
attribute :images do |object, params|
-
6
@host = host
-
-
6
if object.images.attached?
-
object.images.order("index").map { |image|
-
images_response(image)
-
}
-
end
-
end
-
-
1
attribute :compressed_images do |object, params|
-
6
@host = host
-
-
6
if object.compressed_images.attached?
-
object.compressed_images.order("index").map { |image|
-
images_response(image)
-
}
-
end
-
end
-
-
1
attribute :cover_image do |object|
-
6
@host = host
-
6
if object.cover_image.present?
-
img = object.cover_image
-
{
-
file_name: img.try(:blob).try(:filename),
-
content_type: img.try(:blob).try(:content_type),
-
id: img.id,
-
url: img.service_url.split('?').first, only_path: true,
-
width: img.width,
-
height: img.height,
-
dpi: img.dpi,
-
crop_x: img.crop_x,
-
crop_y: img.crop_y,
-
cropWidth: img.crop_width,
-
cropHeight: img.crop_height,
-
created_date: img.created_at,
-
show_date: img.show_date,
-
image_date: img.image_date,
-
image_caption: img.image_caption,
-
face_position: img.face_position,
-
}
-
end
-
end
-
-
1
attributes :book_title do |object|
-
6
if object.present?
-
6
if object.book_title.present?
-
1
object.book_title
-
else
-
5
"#{object&.month} #{object&.year}"
-
end
-
else
-
''
-
end
-
end
-
-
1
class << self
-
1
private
-
-
1
def images_response(image)
-
{
-
file_name: image.try(:blob).try(:filename),
-
content_type: image.try(:blob).try(:content_type),
-
id: image.id,
-
url: image.service_url.split('?').first, only_path: true,
-
image_type: image.image_type,
-
image_caption: image.image_caption,
-
is_cover: image.is_cover,
-
width: image.width,
-
height: image.height,
-
dpi: image.dpi,
-
index: image.index,
-
crop_x: image.crop_x,
-
crop_y: image.crop_y,
-
cropWidth: image.crop_width,
-
cropHeight: image.crop_height,
-
created_date: image.created_at,
-
show_date: image.show_date,
-
image_date: image.image_date,
-
face_position: image.face_position,
-
}
-
end
-
-
1
def host
-
18
Rails.env.development? ? 'http://localhost:3000' : 'https://snapslikeapp2-89023-ruby.b89023.dev.eastus.az.svc.builder.cafe'
-
end
-
end
-
-
end
-
end
-
1
module BxBlockBook
-
1
class BookSizeSerializer < BuilderBase::BaseSerializer
-
1
include JSONAPI::Serializer
-
1
attributes :id, :book_size, :cover_type, :price, :min_limit, :max_limit, :book_size, :created_at, :updated_at
-
end
-
end
-
module BxBlockBook
-
class ContributionSerializer < BuilderBase::BaseSerializer
-
-
# attribute :count do |object, params|
-
# count = 0
-
# account = AccountBlock::Account.find_by(id: object.friend_id)
-
# if (account.id == object.friend_id)
-
# count += 1
-
# end
-
# # count
-
# end
-
-
attribute :images do |object, params|
-
if object.images.attached?
-
object.images.map { |image|
-
{
-
# count: Array.new(AccountBlock::Account.where(id: object.friend_id)).count,
-
username: AccountBlock::Account.find_by(id: object.friend_id).email,
-
url: image.service_url, only_path: true
-
}
-
}
-
end
-
end
-
end
-
end
-
1
module BxBlockBook
-
1
class DeliveryChargeSerializer < BuilderBase::BaseSerializer
-
1
include JSONAPI::Serializer
-
1
attributes :id, :charge, :created_at, :updated_at
-
end
-
end
-
module BxBlockCalendar
-
class AvailabilitySerializer< BuilderBase::BaseSerializer
-
-
attributes *[:service_provider_id,
-
:start_time,
-
:end_time,
-
:unavailable_start_time,
-
:unavailable_end_time,
-
:availability_date,
-
]
-
attribute :booked_slots do |object, params|
-
BxBlockAppointmentManagement::BookedSlot.where(
-
service_provider: object.service_provider
-
).where(
-
booking_date: (Date.parse(params[:date]))
-
).map{|slot| {
-
start_time: slot.start_time,
-
end_time: slot.end_time,
-
booking_date: slot.booking_date
-
}} if params[:date].present?
-
end
-
end
-
end
-
module BxBlockCalendar
-
class BookedSlotSerializer < BuilderBase::BaseSerializer
-
attributes :id, :start_time, :end_time
-
-
attributes :viewable_slot do |object|
-
"#{object.start_time} - #{object.end_time}"
-
end
-
end
-
end
-
module BxBlockCatalogue
-
class BrandSerializer < BuilderBase::BaseSerializer
-
attributes :id, :name, :created_at, :updated_at
-
end
-
end
-
module BxBlockCatalogue
-
class CatalogueSerializer < BuilderBase::BaseSerializer
-
attributes :category, :sub_category, :brand, :tags, :reviews,
-
:name, :sku, :description, :manufacture_date,
-
:length, :breadth, :height, :stock_qty,
-
:availability, :weight, :price, :recommended,
-
:on_sale, :sale_price, :discount
-
-
attribute :images do |object, params|
-
host = params[:host] || ''
-
-
if object.images.attached?
-
object.images.map { |image|
-
{
-
id: image.id,
-
url: host + Rails.application.routes.url_helpers.rails_blob_url(
-
image, only_path: true
-
)
-
}
-
}
-
end
-
end
-
-
attribute :average_rating, &:average_rating
-
-
attribute :catalogue_variants do |object, params|
-
serializer = CatalogueVariantSerializer.new(
-
object.catalogue_variants, { params: params }
-
)
-
serializer.serializable_hash[:data]
-
end
-
end
-
end
-
module BxBlockCatalogue
-
class CatalogueVariantColorSerializer < BuilderBase::BaseSerializer
-
attributes :id, :name, :created_at, :updated_at
-
end
-
end
-
module BxBlockCatalogue
-
class CatalogueVariantSerializer < BuilderBase::BaseSerializer
-
attributes :id, :catalogue_id, :catalogue_variant_color_id,
-
:catalogue_variant_size_id, :price, :stock_qty, :on_sale,
-
:sale_price, :discount_price, :length, :breadth, :height,
-
:created_at, :updated_at
-
-
attribute :images do |object, params|
-
host = params[:host] || ''
-
-
if object.images.attached?
-
object.images.map { |image|
-
{
-
id: image.id,
-
url: host + Rails.application.routes.url_helpers.rails_blob_url(
-
image, only_path: true
-
)
-
}
-
}
-
end
-
end
-
end
-
end
-
module BxBlockCatalogue
-
class CatalogueVariantSizeSerializer < BuilderBase::BaseSerializer
-
attributes :id, :name, :created_at, :updated_at
-
end
-
end
-
module BxBlockCatalogue
-
class ErrorSerializer < BuilderBase::BaseSerializer
-
attribute :errors do |catalogue|
-
catalogue.errors.as_json
-
end
-
end
-
end
-
module BxBlockCatalogue
-
class ReviewSerializer < BuilderBase::BaseSerializer
-
attributes :id, :catalogue_id, :rating, :comment, :created_at, :updated_at
-
end
-
end
-
module BxBlockCatalogue
-
class TagSerializer < BuilderBase::BaseSerializer
-
attributes :id, :name, :created_at, :updated_at
-
end
-
end
-
module BxBlockCategories
-
class CategorySerializer < BuilderBase::BaseSerializer
-
attributes :id, :name, :dark_icon, :dark_icon_active, :dark_icon_inactive, :light_icon,
-
:light_icon_active, :light_icon_inactive, :rank, :created_at, :updated_at
-
-
attribute :dark_icon do |object|
-
object.dark_icon_url
-
end
-
-
attribute :dark_icon_active do |object|
-
object.dark_icon_active_url
-
end
-
-
attribute :dark_icon_inactive do |object|
-
object.dark_icon_inactive_url
-
end
-
-
attribute :light_icon do |object|
-
object.light_icon_url
-
end
-
-
attribute :light_icon_active do |object|
-
object.light_icon_active_url
-
end
-
-
attribute :light_icon_inactive do |object|
-
object.light_icon_inactive_url
-
end
-
-
attribute :sub_categories, if: Proc.new { |record, params|
-
params && params[:sub_categories] == true
-
}
-
-
attribute :selected_sub_categories do |object, params|
-
if params[:selected_sub_categories].present?
-
object.sub_categories.where(id: params[:selected_sub_categories])
-
end
-
end
-
-
end
-
end
-
module BxBlockCategories
-
class CtaSerializer < BuilderBase::BaseSerializer
-
attributes :id, :headline, :description, :category, :is_square_cta, :is_long_rectangle_cta,
-
:is_text_cta, :is_image_cta, :has_button, :button_text, :redirect_url,
-
:visible_on_details_page, :visible_on_home_page, :text_alignment, :button_alignment,
-
:long_background_image, :square_background_image, :created_at, :updated_at
-
-
attribute :long_background_image do |object|
-
object.long_background_image_url
-
end
-
-
attribute :square_background_image do |object|
-
object.square_background_image_url
-
end
-
end
-
end
-
module BxBlockCategories
-
class ErrorSerializer < BuilderBase::BaseSerializer
-
attribute :errors do |coupon|
-
coupon.errors.as_json
-
end
-
end
-
end
-
module BxBlockCategories
-
class SubCategorySerializer < BuilderBase::BaseSerializer
-
attributes :id, :name, :created_at, :updated_at
-
-
attribute :categories, if: Proc.new { |record, params|
-
params && params[:categories] == true
-
}
-
end
-
end
-
module BxBlockContentManagement
-
class AudioPodcastSerializer < BuilderBase::BaseSerializer
-
attributes :id, :heading, :description, :image, :audio, :created_at, :updated_at
-
attributes :image do |object|
-
object.image.image_url if object.image.present?
-
end
-
attributes :audio do |object|
-
object.audio.audio_url if object.audio.present?
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class AuthorSerializer < BuilderBase::BaseSerializer
-
attributes :id, :name, :bio, :created_at, :updated_at
-
attributes :contents do |object|
-
BxBlockContentManagement::ContentSerializer.new(object.contents)
-
end
-
attributes :image do |object|
-
object.image.image_url if object.image.present?
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class BookmarkSerializer < BuilderBase::BaseSerializer
-
attributes :id, :account, :content, :created_at, :updated_at
-
end
-
end
-
module BxBlockContentManagement
-
class ContentProviderSerializer < BuilderBase::BaseSerializer
-
attributes :id, :email, :partner_name, :logo, :created_at, :updated_at
-
-
attribute :follow do |object, params|
-
true if params && params[:current_user_id] && current_user_following(object, params[:current_user_id])
-
end
-
-
-
attribute :logo do |object|
-
object.logo if object.logo.present?
-
end
-
-
class << self
-
private
-
def current_user_following(record, current_user_id)
-
record.follows.where(account_id: current_user_id).present?
-
end
-
end
-
-
end
-
end
-
module BxBlockContentManagement
-
class ContentSerializer < BuilderBase::BaseSerializer
-
attributes :id, :name, :description, :image, :video, :audio, :study_material, :category,
-
:sub_category, :language, :content_type, :contentable, :feature_article,
-
:feature_video, :tag_list, :status, :publish_date, :view_count, :created_at, :updated_at
-
-
attribute :image do |object|
-
object.image if object.image.present?
-
end
-
-
attribute :video do |object|
-
object.video if object.video.present?
-
end
-
-
attribute :audio do |object|
-
object.audio if object.audio.present?
-
end
-
-
attribute :study_material do |object|
-
object.study_material if object.study_material.present?
-
end
-
-
attributes :contentable do |object|
-
case object&.content_type&.type
-
when "Live Stream"
-
BxBlockContentManagement::LiveStreamSerializer.new(object.contentable)
-
when "Videos"
-
BxBlockContentManagement::ContentVideoSerializer.new(object.contentable)
-
when "Text"
-
BxBlockContentManagement::ContentTextSerializer.new(object.contentable)
-
when "AudioPodcast"
-
BxBlockContentManagement::AudioPodcastSerializer.new(object.contentable)
-
when "Test"
-
BxBlockContentManagement::TestSerializer.new(object.contentable)
-
when "Epub"
-
BxBlockContentManagement::EpubSerializer.new(object.contentable)
-
end
-
end
-
-
class << self
-
private
-
def current_user_bookmark(record, current_user_id)
-
record.bookmarks.where(account_id: current_user_id).present?
-
end
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class ContentTextSerializer < BuilderBase::BaseSerializer
-
attributes :id, :headline, :content, :images, :videos,:hyperlink, :affiliation ,:created_at, :updated_at
-
attributes :images do |object|
-
if object.images.present?
-
object.images.each do |image|
-
image.image_url if image.present?
-
end
-
else
-
[]
-
end
-
end
-
attributes :videos do |object|
-
if object.videos.present?
-
object.videos.each do |video|
-
video.video_url if video.present?
-
end
-
else
-
[]
-
end
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class ContentTypeSerializer < BuilderBase::BaseSerializer
-
attributes :id, :name, :type, :identifier, :created_at, :updated_at
-
end
-
end
-
module BxBlockContentManagement
-
class ContentVideoSerializer < BuilderBase::BaseSerializer
-
attributes :id, :separate_section, :headline, :description, :thumbnails, :image, :video, :created_at, :updated_at
-
attributes :image do |object|
-
object.image.image_url if object.image.present?
-
end
-
attributes :video do |object|
-
object.video.video_url if object.video.present?
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class EpubSerializer < BuilderBase::BaseSerializer
-
attributes :id, :heading, :files, :description, :created_at, :updated_at
-
attributes :files do |object|
-
if object.pdfs.present?
-
object.pdfs.each do |pdf|
-
pdf.pdf_url if pdf.present?
-
end
-
else
-
[]
-
end
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class ErrorSerializer < BuilderBase::BaseSerializer
-
attribute :errors do |follow|
-
follow.errors.as_json
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class ExamSerializer < BuilderBase::BaseSerializer
-
attributes :id, :heading, :description, :created_at, :updated_at
-
end
-
end
-
module BxBlockContentManagement
-
class FollowSerializer < BuilderBase::BaseSerializer
-
attributes :id, :account, :content_provider, :created_at, :updated_at
-
end
-
end
-
module BxBlockContentManagement
-
class LiveStreamSerializer < BuilderBase::BaseSerializer
-
attributes :id, :headline, :comment_section, :created_at, :updated_at
-
end
-
end
-
module BxBlockContentManagement
-
class TagSerializer < BuilderBase::BaseSerializer
-
attributes :id, :name, :taggings_count, :created_at, :updated_at
-
end
-
end
-
module BxBlockContentManagement
-
class TestSerializer < BuilderBase::BaseSerializer
-
attributes :id, :description, :created_at, :updated_at
-
end
-
end
-
module BxBlockCouponCg
-
class CouponCodeSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:id,
-
:title,
-
:description,
-
:code,
-
:discount_type,
-
:discount,
-
:valid_from,
-
:valid_to,
-
:min_cart_value,
-
:max_cart_value,
-
:created_at,
-
:updated_at
-
]
-
end
-
end
-
module BxBlockCouponCg
-
class ErrorSerializer < BuilderBase::BaseSerializer
-
attribute :errors do |coupon|
-
coupon.errors.as_json
-
end
-
end
-
end
-
module BxBlockCoupons
-
class SpecialOfferSerializer < BuilderBase::BaseSerializer
-
attributes :id, :name, :sub_title, :active, :discount_percentage,
-
:offer_end_date, :offer_start_date, :final_price
-
-
attribute :logo_url do |object|
-
object.logo.attached? ? object.logo.service_url : nil
-
end
-
-
attribute :services do |object|
-
services_for object
-
end
-
-
class << self
-
private
-
-
def services_for special_offer
-
BxBlockCategories::SubCategorySerializer.new(
-
special_offer.sub_categories, params: {special_offer: special_offer}
-
)
-
end
-
-
def offer_price_for price, discount_percent
-
price - ((price * discount_percent) / 100)
-
end
-
end
-
end
-
end
-
module BxBlockCustomForm
-
class SellerAccountSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
# :activated,
-
:firm_name,
-
:full_phone_number,
-
:location,
-
:country_code,
-
:phone_number,
-
:gstin_number,
-
:wholesaler,
-
:retailer,
-
:manufacturer,
-
:hallmarking_center,
-
:buy_gold,
-
:buy_silver,
-
:sell_gold,
-
:sell_silver,
-
:activated,
-
]
-
end
-
end
-
module BxBlockCustomUserSubs
-
class SubscriptionSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:id,
-
:name,
-
:details,
-
:book_original_price,
-
:no_of_books,
-
:gift_included,
-
:valid_up_to,
-
:total_amount,
-
:subscription_package_amount,
-
:active
-
]
-
-
attribute :expired do |object|
-
object.valid_up_to < Date.today
-
end
-
-
attribute :image_link do |object|
-
object.image.attached? ? Rails.application.routes.url_helpers.rails_blob_path(object.image,only_path: true) : nil
-
end
-
-
attribute :subscribed do |object, params|
-
account = object.user_subscriptions.pluck(:account_id).uniq
-
account.include? params[:user].id
-
end
-
-
end
-
end
-
module BxBlockDashboard
-
class DashboardSerializer < BuilderBase::BaseSerializer
-
attributes :id, :title, :value, :created_at, :updated_at
-
end
-
end
-
module BxBlockDashboard
-
class ErrorSerializer < BuilderBase::BaseSerializer
-
attribute :errors do |coupon|
-
coupon.errors.as_json
-
end
-
end
-
end
-
1
module BxBlockDiscountsoffers
-
1
class OfferSerializer < BuilderBase::BaseSerializer
-
1
attributes :id, :email, :full_phone_number, :title, :description, :code, :min_cart_value, :discount, :discount_type, :valid_from, :valid_to, :coupon_type, :created_at, :updated_at
-
end
-
end
-
module BxBlockEmailNotifications
-
class EmailNotificationSerializer
-
include FastJsonapi::ObjectSerializer
-
attributes *[
-
:id,
-
:notification,
-
:created_at,
-
:updated_at,
-
:send_to_email,
-
:sent_at
-
]
-
end
-
end
-
module BxBlockFavourites
-
class FavouriteSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:favouriteable_id,
-
:favouriteable_type,
-
:favourite_by_id,
-
:created_at,
-
:updated_at,
-
]
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: arrival_windows
-
#
-
# id :bigint not null, primary key
-
# begin_at :datetime
-
# end_at :datetime
-
# exclude_begin :boolean default(TRUE)
-
# exclude_end :boolean default(TRUE)
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
# addressable_id :integer
-
#
-
module BxBlockFedexIntegration
-
class ArrivalWindowSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:exclude_begin,
-
:exclude_end,
-
:begin,
-
:end,
-
]
-
-
attribute :begin do |object|
-
object.begin_at
-
end
-
-
attribute :end do |object|
-
object.end_at
-
end
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: cod_values
-
#
-
# id :bigint not null, primary key
-
# shipment_id :bigint not null
-
# amount :float
-
# currency :string default("RS")
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
#
-
module BxBlockFedexIntegration
-
class CodValueSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:amount,
-
:currency,
-
]
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: coordinates
-
#
-
# id :bigint not null, primary key
-
# latitude :string
-
# longitude :string
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
# addressable_id :integer
-
#
-
module BxBlockFedexIntegration
-
class CoordinateSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:latitude,
-
:longitude,
-
]
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: create_shipments
-
#
-
# id :bigint not null, primary key
-
# auto_assign_drivers :boolean default(FALSE)
-
# requested_by :string
-
# shipper_id :string
-
# waybill :string
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
#
-
module BxBlockFedexIntegration
-
class CreateShipmentSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:auto_assign_drivers,
-
:requested_by,
-
:shipper_id,
-
:shipments,
-
]
-
-
attribute :shipments do |object|
-
ShipmentSerializer
-
.new(object.shipments)
-
.serializable_hash[:data]
-
.map { |data| data[:attributes] }
-
end
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: addressables
-
#
-
# id :bigint not null, primary key
-
# shipment_id :bigint not null
-
# address :text
-
# address2 :text
-
# city :string
-
# country :string
-
# email :string
-
# name :string
-
# phone :string
-
# instructions :text
-
# type :string
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
#
-
module BxBlockFedexIntegration
-
class DeliverySerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:address,
-
:address2,
-
:city,
-
:country,
-
:email,
-
:name,
-
:phone,
-
:instructions,
-
:arrival_window,
-
:coordinate,
-
]
-
-
attribute :arrival_window do |object|
-
ArrivalWindowSerializer
-
.new(object.arrival_window)
-
.serializable_hash[:data][:attributes]
-
end
-
-
attribute :coordinate do |object|
-
CoordinateSerializer
-
.new(object.coordinate)
-
.serializable_hash[:data][:attributes]
-
end
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: dimensions
-
#
-
# id :bigint not null, primary key
-
# item_id :bigint not null
-
# height :float
-
# length :float
-
# width :float
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
#
-
module BxBlockFedexIntegration
-
class DimensionSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:height,
-
:length,
-
:width,
-
]
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: items
-
#
-
# id :bigint not null, primary key
-
# shipment_id :bigint not null
-
# ref_id :string
-
# weight :float
-
# quantity :integer
-
# stackable :boolean default(TRUE)
-
# item_type :integer default("PALLET")
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
#
-
module BxBlockFedexIntegration
-
class ItemSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:ref_id,
-
:weight,
-
:quantity,
-
:stackable,
-
:type,
-
:dimensions,
-
]
-
-
attribute :type do |object|
-
object.item_type
-
end
-
-
attribute :dimensions do |object|
-
DimensionSerializer
-
.new(object.dimension)
-
.serializable_hash[:data][:attributes]
-
end
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: addressables
-
#
-
# id :bigint not null, primary key
-
# shipment_id :bigint not null
-
# address :text
-
# address2 :text
-
# city :string
-
# country :string
-
# email :string
-
# name :string
-
# phone :string
-
# instructions :text
-
# type :string
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
#
-
module BxBlockFedexIntegration
-
class PickupSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:address,
-
:address2,
-
:city,
-
:country,
-
:email,
-
:name,
-
:phone,
-
:arrival_window,
-
:coordinate,
-
]
-
-
attribute :arrival_window do |object|
-
ArrivalWindowSerializer
-
.new(object.arrival_window)
-
.serializable_hash[:data][:attributes]
-
end
-
-
attribute :coordinate do |object|
-
CoordinateSerializer
-
.new(object.coordinate)
-
.serializable_hash[:data][:attributes]
-
end
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: shipments
-
#
-
# id :bigint not null, primary key
-
# create_shipment_id :bigint not null
-
# ref_id :string
-
# full_truck :boolean default(FALSE)
-
# load_description :text
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
#
-
module BxBlockFedexIntegration
-
class ShipmentSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:ref_id,
-
:full_truck,
-
:load_description,
-
:cod_value,
-
:shipment_value,
-
:delivery,
-
:pickup,
-
:items,
-
]
-
-
attribute :cod_value do |object|
-
CodValueSerializer
-
.new(object.cod_value)
-
.serializable_hash[:data][:attributes]
-
end
-
-
attribute :shipment_value do |object|
-
ShipmentValueSerializer
-
.new(object.shipment_value)
-
.serializable_hash[:data][:attributes]
-
end
-
-
attribute :delivery do |object|
-
DeliverySerializer
-
.new(object.delivery)
-
.serializable_hash[:data][:attributes]
-
end
-
-
attribute :pickup do |object|
-
PickupSerializer
-
.new(object.pickup)
-
.serializable_hash[:data][:attributes]
-
end
-
-
attribute :items do |object|
-
ItemSerializer
-
.new(object.items)
-
.serializable_hash[:data]
-
.map { |data| data[:attributes] }
-
end
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: shipment_values
-
#
-
# id :bigint not null, primary key
-
# shipment_id :bigint not null
-
# amount :float
-
# currency :string
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
#
-
module BxBlockFedexIntegration
-
class ShipmentValueSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:amount,
-
:currency,
-
]
-
end
-
end
-
1
module BxBlockForgotPassword
-
1
class EmailOtpSerializer < BuilderBase::BaseSerializer
-
1
attributes :email, :created_at
-
1
attributes :pin
-
end
-
end
-
1
module BxBlockForgotPassword
-
1
class SmsOtpSerializer < BuilderBase::BaseSerializer
-
1
attributes :full_phone_number, :activated, :created_at
-
1
attributes :pin, :valid_until
-
end
-
end
-
module BxBlockGallery
-
class PhotoSerializer < BuilderBase::BaseSerializer
-
include JSONAPI::Serializer
-
attributes :id, :month_year, :month_range, :title, :year, :month, :image_caption, :photo_type, :created_at
-
-
attribute :images do |object, params|
-
host = params[:host] || ''
-
-
if object.images.attached?
-
object.images.map { |image|
-
{
-
id: image.id,
-
url: host + Rails.application.routes.url_helpers.rails_blob_url(
-
image, only_path: true
-
)
-
}
-
}
-
end
-
end
-
-
attribute :length do |object|
-
if object.images.attached?
-
object.images.length
-
end
-
end
-
end
-
end
-
module BxBlockHelpCentre
-
class QuestionAnswerSerializer < BuilderBase::BaseSerializer
-
include FastJsonapi::ObjectSerializer
-
attributes *[
-
:id,
-
:question,
-
:answer,
-
:created_at,
-
:updated_at
-
]
-
end
-
end
-
module BxBlockHelpCentre
-
class QuestionSubTypeSerializer < BuilderBase::BaseSerializer
-
include FastJsonapi::ObjectSerializer
-
attributes *[
-
:id,
-
:sub_type,
-
:description,
-
:created_at,
-
:updated_at,
-
:question_answers
-
]
-
attribute :question_answers do |object|
-
BxBlockHelpCentre::QuestionAnswerSerializer.new(object.question_answers)
-
end
-
end
-
end
-
module BxBlockHelpCentre
-
class QuestionTypeSerializer < BuilderBase::BaseSerializer
-
include FastJsonapi::ObjectSerializer
-
attributes *[
-
:id,
-
:que_type,
-
:description,
-
:created_at,
-
:updated_at,
-
:question_sub_types
-
]
-
attribute :question_sub_types do |object|
-
BxBlockHelpCentre::QuestionSubTypeSerializer.new(object.question_sub_types)
-
end
-
end
-
end
-
module BxBlockLanguageOptions
-
class ApplicationMessageSerializer < BuilderBase::BaseSerializer
-
attributes :id, :name, :created_at, :updated_at
-
-
attribute :translations do |object|
-
TranslationSerializer.new(object.translations)
-
end
-
-
end
-
end
-
module BxBlockLanguageOptions
-
class LanguageSerializer < BuilderBase::BaseSerializer
-
attributes :id, :name, :language_code, :created_at, :updated_at
-
end
-
end
-
module BxBlockLanguageOptions
-
class TranslationSerializer < BuilderBase::BaseSerializer
-
attributes :locale, :message
-
end
-
end
-
module BxBlockLike
-
class LikeSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:likeable_id,
-
:likeable_type,
-
:like_by_id,
-
:created_at,
-
:updated_at,
-
]
-
end
-
end
-
module BxBlockLocation
-
class VanLocationSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:latitude,
-
:longitude,
-
]
-
-
attribute :van do |object|
-
object.van
-
end
-
-
attribute :service_provider do |object|
-
AccountBlock::AccountSerializer.new(object.van.service_provider)
-
end
-
-
attribute :distance do |object, params|
-
if params.present? && params[:coordinates].present?
-
van_location = [object.latitude, object.longitude]
-
find_distance_between_coordinates(params[:coordinates], van_location)
-
else
-
nil
-
end
-
end
-
-
class << self
-
def find_distance_between_coordinates start_address_coordinates, van_location
-
Geocoder::Calculations.distance_between(start_address_coordinates, van_location, units: :km)
-
end
-
end
-
end
-
end
-
module BxBlockNotifications
-
class NotificationSerializer
-
include FastJsonapi::ObjectSerializer
-
attributes *[
-
:id,
-
:created_by,
-
:headings,
-
:contents,
-
:app_url,
-
:is_read,
-
:read_at,
-
:created_at,
-
:updated_at,
-
:account
-
]
-
end
-
end
-
module BxBlockOrderManagement
-
class AddressesSerializer < BuilderBase::BaseSerializer
-
-
attributes *[
-
:id,
-
:name,
-
:flat_no,
-
:address,
-
:address_type,
-
:address_line_2,
-
:zip_code,
-
:phone_number,
-
:latitude,
-
:longitude,
-
:address_for,
-
:is_default,
-
:address_type,
-
:city,
-
:state,
-
:country,
-
:landmark,
-
:created_at,
-
:updated_at,
-
:account
-
]
-
-
attribute :account, if: Proc.new { |rec, params| params[:user].present? }
-
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: delivery_address_orders
-
#
-
# id :bigint not null, primary key
-
# order_id :bigint not null
-
# delivery_address_id :bigint not null
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
#
-
require_relative 'addresses_serializer'
-
-
module BxBlockOrderManagement
-
class DeliveryAddressOrderSerializer < BuilderBase::BaseSerializer
-
-
belongs_to :delivery_address, serializer: AddressesSerializer
-
-
attributes *[
-
:id,
-
:order_id,
-
:delivery_address_id,
-
:created_at,
-
:updated_at,
-
:delivery_address
-
]
-
-
end
-
-
end
-
# == Schema Information
-
#
-
# Table name: order_items
-
#
-
# id :bigint not null, primary key
-
# order_id :bigint not null
-
# quantity :integer
-
# unit_price :decimal(, )
-
# total_price :decimal(, )
-
# old_unit_price :decimal(, )
-
# status :string
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
# catalogue_id :bigint not null
-
# catalogue_variant_id :bigint not null
-
# order_status_id :integer
-
# placed_at :datetime
-
# confirmed_at :datetime
-
# in_transit_at :datetime
-
# delivered_at :datetime
-
# cancelled_at :datetime
-
# refunded_at :datetime
-
# manage_placed_status :boolean default(FALSE)
-
# manage_cancelled_status :boolean default(FALSE)
-
#
-
module BxBlockOrderManagement
-
class OrderItemSerializer < BuilderBase::BaseSerializer
-
-
attributes *[
-
:id,
-
:order_id,
-
:quantity,
-
:unit_price,
-
:total_price,
-
:old_unit_price,
-
:status,
-
:catalogue_id,
-
:catalogue_variant_id,
-
:order_status_id,
-
:placed_at,
-
:confirmed_at,
-
:in_transit_at,
-
:delivered_at,
-
:cancelled_at,
-
:refunded_at,
-
:manage_placed_status,
-
:manage_cancelled_status,
-
:created_at,
-
:updated_at
-
]
-
-
attribute :order, if: Proc.new { |rec,params| params[:order].present? }
-
attribute :order_statuses do |object, params|
-
if params.present?
-
order = object.order
-
{
-
order_number: order.order_number,
-
placed_at: order.placed_at,
-
confirmed_at: order.confirmed_at,
-
in_transit_at: order.in_transit_at,
-
delivered_at: order.delivered_at,
-
cancelled_at: order.cancelled_at,
-
refunded_at: order.refunded_at,
-
}
-
end
-
end
-
-
attribute :delivery_addresses do |object,params|
-
if params[:order] == true && object.present?
-
object.order&.delivery_addresses
-
end
-
end
-
-
attribute :catalogue do |object, params|
-
if object.present?
-
BxBlockCatalogue::CatalogueSerializer.new(
-
object.catalogue, { params: params }
-
).serializable_hash[:data]
-
end
-
end
-
-
-
-
-
end
-
end
-
# == Schema Information
-
#
-
# Table name: orders
-
#
-
# id :bigint not null, primary key
-
# order_number :string
-
# amount :float
-
# created_at :datetime not null
-
# updated_at :datetime not null
-
# account_id :bigint
-
# coupon_code_id :bigint
-
# delivery_address_id :bigint
-
# sub_total :decimal(, ) default(0.0)
-
# total :decimal(, ) default(0.0)
-
# status :string
-
# applied_discount :decimal(, ) default(0.0)
-
# cancellation_reason :text
-
# order_date :datetime
-
# is_gift :boolean default(FALSE)
-
# placed_at :datetime
-
# confirmed_at :datetime
-
# in_transit_at :datetime
-
# delivered_at :datetime
-
# cancelled_at :datetime
-
# refunded_at :datetime
-
# source :string
-
# shipment_id :string
-
# delivery_charges :string
-
# tracking_url :string
-
# schedule_time :datetime
-
# payment_failed_at :datetime
-
# returned_at :datetime
-
# tax_charges :decimal(, ) default(0.0)
-
# deliver_by :integer
-
# tracking_number :string
-
# is_error :boolean default(FALSE)
-
# delivery_error_message :string
-
# payment_pending_at :datetime
-
# order_status_id :integer
-
# is_group :boolean default(TRUE)
-
# is_availability_checked :boolean default(FALSE)
-
# shipping_charge :decimal(, )
-
# shipping_discount :decimal(, )
-
# shipping_net_amt :decimal(, )
-
# shipping_total :decimal(, )
-
# total_tax :float
-
#
-
1
module BxBlockOrderManagement
-
1
class OrderSerializer < BuilderBase::BaseSerializer
-
-
1
attributes *[
-
:id,
-
:order_number,
-
:amount,
-
:account_id,
-
:coupon_code_id,
-
:delivery_address_id,
-
:sub_total,
-
:status,
-
:applied_discount,
-
:cancellation_reason,
-
:order_date,
-
:is_gift,
-
:placed_at,
-
:confirmed_at,
-
:in_transit_at,
-
:delivered_at,
-
:cancelled_at,
-
:refunded_at,
-
:source,
-
:shipment_id,
-
:delivery_charges,
-
:tracking_url,
-
:schedule_time,
-
:payment_failed_at,
-
:payment_pending_at,
-
:returned_at,
-
:tax_charges,
-
:deliver_by,
-
:tracking_number,
-
:is_error,
-
:delivery_error_message,
-
:order_status_id,
-
:is_group,
-
:is_availability_checked,
-
:shipping_charge,
-
:shipping_discount,
-
:shipping_net_amt,
-
:shipping_total,
-
:total_tax,
-
:created_at,
-
:updated_at,
-
:delivery_addresses,
-
:razorpay_order_id,
-
:no_of_pages,
-
:book_size,
-
:book_title,
-
:book_color,
-
:book_url,
-
:cover_type,
-
:paper_type,
-
:book_id,
-
:no_of_pages,
-
:quantity,
-
:gift_note,
-
:image,
-
:title_layout,
-
:order_child_id,
-
:additional_pages,
-
:total,
-
:additional_price,
-
:base_price,
-
:sharable_code,
-
:cover_image
-
]
-
-
1
attribute :image do |object|
-
19
book = BxBlockBook::Book.find_by(id: object.book_id)
-
19
book&.images&.where(is_cover: true)&.first.present? ? book&.images&.where(is_cover: true)&.first&.service_url : book&.images&.first&.service_url
-
end
-
-
1
attribute :cover_image do |object|
-
19
book = BxBlockBook::Book.find_by(id: object.book_id)
-
19
book&.cover_image&.present? ? book&.cover_image&.service_url : ""
-
end
-
-
1
attribute :book_title do |object|
-
19
book = BxBlockBook::Book.find_by(id: object.book_id)
-
19
book&.book_title.present? ? book&.book_title : "#{book&.month} #{book&.year}"
-
end
-
-
1
attribute :spine_title do |object|
-
19
book = BxBlockBook::Book.find_by(id: object.book_id)
-
19
book&.spine_title
-
end
-
-
1
attribute :title_color do |object|
-
19
book = BxBlockBook::Book.find_by(id: object.book_id)
-
19
book&.title_color
-
end
-
-
1
attribute :logo_color do |object|
-
19
book = BxBlockBook::Book.find_by(id: object.book_id)
-
19
book&.logo_color
-
end
-
-
1
attribute :book_color do |object|
-
19
book = BxBlockBook::Book.find_by(id: object.book_id)
-
19
if book.present? && book&.book_color.present?
-
book&.book_color
-
19
elsif book.present? && object&.book_color.present?
-
object&.book_color
-
else
-
19
"black"
-
end
-
end
-
-
1
attribute :book_url do |object|
-
19
object&.book_url.present? ? object&.book_url : ''
-
end
-
-
1
attribute :title_layout do |object|
-
19
book = BxBlockBook::Book.find_by(id: object.book_id)
-
19
book&.title_layout.present? ? book&.title_layout : ''
-
end
-
-
1
attribute :max_order_refers do |object|
-
19
limit = BxBlockReferrals::ReferralLimitSetting.where(active: true).last
-
19
limit&.max_order_refers
-
end
-
-
1
attribute :coupon_details do |object|
-
19
if object&.coupon_code_id.present?
-
5
BxBlockDiscountsoffers::Offer.find_by(id: object.coupon_code_id)
-
else
-
14
nil
-
end
-
end
-
-
1
attribute :address do |object|
-
19
if object&.address.present?
-
object&.address
-
else
-
19
nil
-
end
-
end
-
end
-
end
-
1
module BxBlockOrdersummary
-
1
class OrderSummarySerializer < BuilderBase::BaseSerializer
-
1
attributes *[
-
:id,
-
:quantity,
-
:gift_note,
-
:discount_code,
-
:order_subtotal,
-
:book_id,
-
:delivery_charge,
-
:book_size,
-
:cover_type,
-
:order_total,
-
:created_at,
-
:updated_at
-
]
-
end
-
end
-
module BxBlockPaymentRazorpay
-
class CaptureResponseSerializer < BuilderBase::BaseSerializer
-
attributes :id, :entity, :amount, :currency, :status, :order_id,
-
:invoice_id, :international, :method, :captured, :description,
-
:email, :contact, :error_code, :error_description
-
end
-
end
-
module BxBlockPaymentRazorpay
-
class OrderDetailsSerializer < BuilderBase::BaseSerializer
-
attributes :id, :entity, :amount, :amount_paid, :amount_due, :currency,
-
:receipt, :offer_id, :status, :attempts, :notes, :created_at
-
end
-
end
-
module BxBlockPosts
-
class ErrorSerializer < BuilderBase::BaseSerializer
-
attribute :errors do |post|
-
post.errors.as_json
-
end
-
end
-
end
-
module BxBlockPosts
-
class PostSerializer < BuilderBase::BaseSerializer
-
-
attributes *[
-
:id,
-
:name,
-
:description,
-
:body,
-
:location,
-
:account_id,
-
:created_at,
-
:updated_at
-
]
-
-
attribute :model_name do |object|
-
object.class.name
-
end
-
-
attribute :images_and_videos do |object|
-
object.images.attached? ?
-
object.images.map { |img|
-
{
-
id: img.id, filename: img.filename,
-
url: Rails.application.routes.url_helpers.url_for(img),
-
type: img.blob.content_type.split('/')[0]
-
}
-
} : []
-
end
-
-
attribute :media do |object|
-
object.media_url
-
end
-
-
attribute :created_at do |object|
-
"#{time_ago_in_words(object.created_at)} ago"
-
end
-
end
-
end
-
module BxBlockPrivacySettings
-
class AboutUsSerializer < BuilderBase::BaseSerializer
-
include JSONAPI::Serializer
-
attributes *[
-
:id,
-
:content,
-
:description
-
]
-
end
-
end
-
module BxBlockPrivacySettings
-
class ActivitySettingSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:account_id,
-
:latest_activity,
-
:older_activity
-
]
-
end
-
end
-
module BxBlockPrivacySettings
-
class NotificationSettingSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:account_id,
-
:in_app_notification,
-
:chat_notification,
-
:friend_request,
-
:interest_received,
-
:viewed_profile,
-
:off_all_notification
-
]
-
end
-
end
-
module BxBlockPrivacySettings
-
class PrivacyPolicySerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:id,
-
:content
-
]
-
end
-
end
-
module BxBlockPrivacySettings
-
class PrivacySettingSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:account_id
-
]
-
-
attribute :full_name do |object|
-
account = object.account
-
return nil if account.first_name.blank? and account.last_name.blank?
-
[account&.first_name, account&.last_name].join(" ")
-
end
-
-
attribute :is_online do |object|
-
object.account.online?
-
end
-
-
attribute :profile_image do |object|
-
image_hash = {}
-
if object.account.images.attached?
-
img = object.account.images.find_by(default_image: true)
-
image_hash = {
-
id: img.id,
-
url: Rails.application.routes.url_helpers.url_for(img),
-
default_image: img.default_image
-
} if img.present?
-
end
-
image_hash
-
end
-
end
-
end
-
module BxBlockPrivacySettings
-
class TermsAndConditionsSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:content
-
]
-
end
-
end
-
module BxBlockProfile
-
class AwardSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:title,
-
:associated_with,
-
:issuer,
-
:issue_date,
-
:description,
-
:make_public
-
]
-
end
-
end
-
module BxBlockProfile
-
class CareerExperienceSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:id,
-
:job_title,
-
:start_date,
-
:end_date,
-
:company_name,
-
:description,
-
:add_key_achievements,
-
:make_key_achievements_public,
-
:profile_id,
-
:current_salary,
-
:currently_working_here,
-
:notice_period,
-
:notice_period_end_date
-
]
-
-
attributes :career_experience_industrys do |object|
-
object.career_experience_industrys.map do |car_ind|
-
{
-
id: car_ind.industry.id,
-
industry_name: car_ind.industry.industry_name
-
}
-
end
-
end
-
-
attributes :career_experience_employment_types do |object|
-
object.career_experience_employment_types.map do |car_emp|
-
{
-
id:car_emp.employment_type.id,
-
employment_type_name: car_emp.employment_type.employment_type_name
-
}
-
end
-
end
-
-
attributes :career_experience_system_experiences do |object|
-
object.career_experience_system_experiences.map do |car_exp|
-
{
-
id:car_exp.system_experience.id,
-
system_experience: car_exp.system_experience.system_experience
-
}
-
end
-
end
-
-
end
-
end
-
module BxBlockProfile
-
class CourseSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:course_name,
-
:duration,
-
:year
-
]
-
end
-
end
-
module BxBlockProfile
-
class CurrentStatusSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:most_recent_job_title,
-
:company_name,
-
:notice_period,
-
:end_date,
-
:profile_id
-
]
-
-
attributes :current_status_industrys do |object|
-
object.current_status_industrys.map do |cur_ind|
-
{
-
id: cur_ind.industry.id,
-
industry_name: cur_ind.industry.industry_name
-
}
-
end
-
end
-
-
attributes :current_status_employment_types do |object|
-
object.current_status_employment_types.map do |cur_emp|
-
{
-
id:cur_emp.employment_type.id,
-
employment_type_name: cur_emp.employment_type.employment_type_name
-
}
-
end
-
end
-
-
attributes :current_annual_salary_current_status do |object|
-
object.current_annual_salary_current_status.map do |sal_stat|
-
{
-
id:sal_stat.current_annual_salary.id,
-
employment_type_name: sal_stat.current_annual_salary.current_annual_salary
-
}
-
end
-
end
-
-
end
-
end
-
module BxBlockProfile
-
class DegreeSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:id,
-
:degree_name
-
]
-
end
-
end
-
module BxBlockProfile
-
class EducationalQualificationSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:id,
-
:school_name,
-
:start_date,
-
:end_date,
-
:grades,
-
:description,
-
:make_grades_public,
-
:profile_id
-
]
-
attributes :educational_qualification_field_studys do |object|
-
object.educational_qualification_field_studys.map do |edu_qual|
-
{
-
id: edu_qual.field_study.id,
-
field_of_study: edu_qual.field_study.field_of_study
-
}
-
end
-
end
-
-
attributes :degree_educational_qualifications do |object|
-
object.degree_educational_qualifications.map do |deg_qual|
-
{
-
id:deg_qual.degree.id,
-
degree_name: deg_qual.degree.degree_name
-
}
-
end
-
end
-
end
-
end
-
module BxBlockProfile
-
class HobbySerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:title,
-
:category,
-
:description,
-
:make_public
-
]
-
end
-
end
-
module BxBlockProfile
-
class IndustrySerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:id,
-
:industry_name
-
]
-
end
-
end
-
module BxBlockProfile
-
class LanguageSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:id,
-
:language,
-
:proficiency,
-
:profile_id
-
]
-
end
-
end
-
module BxBlockProfile
-
class ProfileSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:id,
-
:country,
-
:address,
-
:city,
-
:postal_code,
-
:account_id,
-
:profile_role
-
]
-
-
attributes :photo do |object|
-
Rails.application.routes.url_helpers.rails_blob_path(object.photo, only_path: true) if object.photo.attached?
-
end
-
-
end
-
end
-
module BxBlockProfile
-
class ProjectSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:id,
-
:project_name,
-
:start_date,
-
:end_date,
-
:add_members,
-
:url,
-
:description,
-
:make_projects_public,
-
:profile_id
-
]
-
-
attributes :associated_projects do |object|
-
object.associated_projects.map do |ass_pro|
-
{
-
id: ass_pro.associated.id,
-
associated_with_name: ass_pro.associated.associated_with_name
-
}
-
end
-
end
-
-
end
-
end
-
module BxBlockProfile
-
class PublicationPatentSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:title,
-
:publication,
-
:authors,
-
:url,
-
:description,
-
:make_public,
-
:profile_id
-
]
-
end
-
end
-
module BxBlockProfile
-
class TestScoreAndCourseSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:title,
-
:associated_with,
-
:score,
-
:test_date,
-
:description,
-
:make_public
-
]
-
end
-
end
-
module BxBlockPushNotifications
-
class PushNotificationSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:push_notificable_id,
-
:push_notificable_type,
-
:remarks,
-
:is_read,
-
:created_at,
-
:updated_at
-
]
-
-
attribute :account do |object|
-
AccountBlock::SmsAccountSerializer.new(object.account)
-
end
-
-
attribute :looking_for do |object|
-
object.account&.categories&.map(&:name)
-
end
-
-
attribute :profile_image do |object, params|
-
image_hash = {}
-
img = nil
-
img = object.account.images.find_by(default_image: true) if object.account.images.attached?
-
image_hash = {
-
id: img.id,
-
url: Rails.application.routes.url_helpers.url_for(img),
-
default_image: img.default_image
-
} if img.present?
-
image_hash
-
end
-
end
-
end
-
1
module BxBlockReferrals
-
1
class ReferralSerializer < BuilderBase::BaseSerializer
-
1
attributes *[
-
:id,
-
:referral_code,
-
:referral_by,
-
:referal_count,
-
:code_used,
-
:account_id,
-
:offer_id
-
]
-
end
-
end
-
module BxBlockRequestManagement
-
class RequestSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:sender_id,
-
:account_id,
-
:status,
-
:created_at,
-
:updated_at,
-
]
-
-
attribute :full_name do |object, params|
-
if object.sender_id == params[:current_user][:id]
-
[object.account&.first_name, object.account&.last_name].join(" ")
-
else
-
[object.sender&.first_name, object.sender&.last_name].join(" ")
-
end
-
end
-
-
attribute :mutual_friends_count do |object|
-
object.mutual_friends&.count
-
end
-
end
-
end
-
module BxBlockReviews
-
class ErrorSerializer < BuilderBase::BaseSerializer
-
attribute :errors do |review|
-
review.errors.as_json
-
end
-
end
-
end
-
module BxBlockReviews
-
class ReviewSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:id,
-
:title,
-
:description,
-
:account_id,
-
:created_at
-
]
-
-
attribute :reviewer do |object|
-
AccountBlock::AccountSerializer.new(object.reviewer).serializable_hash unless object.anonymous
-
end
-
-
end
-
end
-
module BxBlockSettings
-
class SettingSerializer < BuilderBase::BaseSerializer
-
attributes *[
-
:name,
-
:title
-
]
-
end
-
end
-
module BxBlockShoppingCart
-
class AvailabilitySerializer< BuilderBase::BaseSerializer
-
-
attributes *[:service_provider_id,
-
:start_time,
-
:end_time,
-
:unavailable_start_time,
-
:unavailable_end_time,
-
:availability_date,
-
]
-
attribute :booked_slots do |object, params|
-
object.service_provider.booked_slots.where(
-
booking_date: (Date.parse(params[:date]))
-
).map{
-
|slot| {
-
start_time: slot.start_time,
-
end_time: slot.end_time,
-
booking_date: slot.booking_date
-
}
-
} if params.present? && params[:date].present?
-
end
-
end
-
end
-
module BxBlockShoppingCart
-
class OrderSerializer < BuilderBase::BaseSerializer
-
-
attributes *[
-
:booking_date,
-
:slot_start_time,
-
:total_fees,
-
:instructions,
-
:service_total_time_minutes,
-
:status,
-
:is_coupon_applied,
-
:ongoing_time,
-
:finish_at,
-
:notify_me,
-
]
-
-
attribute :service_provider do |object|
-
AccountBlock::AccountSerializer.new(object.service_provider)
-
end
-
-
attribute :customer do |object|
-
AccountBlock::AccountSerializer.new(object.customer)
-
end
-
-
attribute :booked_slot do |object|
-
BxBlockCalendar::BookedSlotSerializer.new(object.booked_slot)
-
end
-
-
attribute :van_location do |object|
-
van_member = BxBlockLocation::VanMember.find_by_account_id(object.service_provider.id)
-
van = BxBlockLocation::Van.find_by_id(van_member.van_id)
-
BxBlockLocation::VanLocationSerializer.new(
-
van.location
-
) if van&.location.present?
-
end
-
-
attribute :address do |object|
-
BxBlockAddress::AddressSerializer.new(object.address)
-
end
-
-
attribute :services do |object|
-
order_services_for object
-
end
-
-
attribute :coupon_detail do |object|
-
object.is_coupon_applied ? object.coupon&.name : nil
-
end
-
-
class << self
-
def order_services_for order
-
order.sub_categories.pluck(:name)
-
# order.services.map{|service| service.sub_category.name }
-
end
-
end
-
end
-
end
-
module BxBlockShoppingCart
-
class OrderServicesSerializer < BuilderBase::BaseSerializer
-
-
attributes :service_provider_id do |data|
-
data.service_provider_id
-
end
-
-
attributes :service_id do |data|
-
data.id
-
end
-
end
-
end
-
module BxBlockStories
-
class BlogsSerializer < BuilderBase::BaseSerializer
-
include JSONAPI::Serializer
-
attributes :id, :description, :status, :title, :url
-
-
attribute :blog_file do |object, params|
-
if object&.blog_file.attached?
-
ENV['HOST_URL'] + Rails.application.routes.url_helpers.rails_blob_url(object.blog_file, only_path: true)
-
end
-
end
-
end
-
end
-
module BxBlockStories
-
class ErrorSerializer < BuilderBase::BaseSerializer
-
attribute :errors do |story|
-
story.errors.as_json
-
end
-
end
-
end
-
1
module BxBlockStories
-
1
class StorySerializer < BuilderBase::BaseSerializer
-
1
include JSONAPI::Serializer
-
1
attributes :id, :description, :valid_till, :active, :title, :story_type, :link
-
-
1
attribute :story_file do |object, params|
-
1
if object&.story_file.attached?
-
ENV['HOST_URL'] + Rails.application.routes.url_helpers.rails_blob_url(object.story_file, only_path: true)
-
end
-
end
-
end
-
end
-
require 'active_storage/downloading'
-
module AccountBlock
-
class DocxDownloadService
-
include ActiveStorage::Downloading
-
attr_reader :blob
-
-
def initialize(blob)
-
@blob = blob
-
end
-
-
def doc
-
download_blob_to_tempfile do |file|
-
File.read(file)
-
end
-
end
-
end
-
end
-
1
module AccountBlock
-
1
class EmailValidation
-
1
include ActiveModel::Validations
-
-
1
attr_reader :email
-
-
1
class << self
-
1
def regex
-
1
/[^@]+[@][\S]+[.][\S]+/
-
end
-
-
1
def regex_string
-
regex.to_s.sub('(?-mix:', '').delete_suffix(')')
-
end
-
end
-
-
1
validates :email, :format => {
-
:with => regex,
-
:multiline => true,
-
}
-
-
1
def initialize(email)
-
3
@email = email
-
end
-
end
-
end
-
module AccountBlock
-
class PasswordValidation
-
include ActiveModel::Validations
-
-
attr_reader :password
-
-
class << self
-
def regex
-
# ^ Start anchor
-
# (?=.*[A-Z]) Has one uppercase letter
-
# (?=.*[!@#$&*?<>',\[\]}{=\-)(^%`~+.:;_]) Has one special case symbol
-
# (?=.*[0-9]) Has one digit
-
# (?=.*[a-z]) Has one lowercase letter
-
# .{8,} Is at least length 8
-
# $ End anchor
-
/^(?=.*[A-Z])(?=.*[#!@$&*?<>',\[\]}{=\-)(^%`~+.:;_])(?=.*[0-9])(?=.*[a-z]).{8,}$/
-
end
-
-
def regex_string
-
regex.to_s.sub('(?-mix:', '').delete_suffix(')')
-
end
-
-
def rules
-
'Password should be a minimum of 8 characters long,' \
-
' contain both uppercase and lowercase characters, at' \
-
' least one digit, and one special character ' \
-
'(!@#$&*?<>\',[]}{=-)(^%`~+.:;_).'
-
end
-
end
-
-
validates :password, :format => {
-
:with => regex,
-
:multiline => true,
-
}
-
-
def initialize(password)
-
@password = password
-
end
-
end
-
end
-
module AccountBlock
-
class PhoneValidation
-
include ActiveModel::Validations
-
-
attr_accessor :phone
-
-
validate :validate_phone
-
-
def initialize(phone)
-
@phone = phone
-
end
-
-
private
-
-
def validate_phone
-
return if Phonelib.valid?(@phone)
-
errors.add :phone_number, 'is not valid'
-
end
-
end
-
end
-
1
module BuilderJsonWebToken
-
1
class JsonWebToken
-
1
attr_reader :id, :expiration
-
-
1
class << self
-
1
def encode(id, data = {}, expiration = nil)
-
87
expiration, data = data, expiration unless data.is_a?(Hash)
-
-
87
data ||= {}
-
87
expiration ||= 1.month.from_now
-
-
87
payload = build_payload_for(id.to_i, data, expiration.to_i)
-
-
87
JWT.encode payload, secret_key, algorithm
-
end
-
-
1
def decode(token)
-
50
JsonWebToken.new token_data_for(token)
-
end
-
-
1
private
-
-
1
def token_data_for(token)
-
50
JWT.decode(token, secret_key, true, {
-
:algorithm => algorithm,
-
})[0]
-
end
-
-
1
def build_payload_for(id, data, expiration)
-
{
-
87
:id => id,
-
:exp => expiration,
-
}.merge(data)
-
end
-
-
1
def secret_key
-
137
@secret_key ||= Rails.application.secret_key_base
-
end
-
-
1
def algorithm
-
137
'HS512'
-
end
-
end
-
-
1
def initialize(data)
-
49
@id = data.delete('id')
-
49
@expiration = Time.at(data.delete('exp')).to_time
-
49
@struct = nil
-
49
initialize_attributes_for data if data.is_a?(Hash) && data.keys.any?
-
end
-
-
1
private
-
-
1
def initialize_attributes_for(data)
-
@struct = Struct.new(*data.keys.map(&:to_sym)).new
-
data.keys.each do |key|
-
@struct.send("#{key}=", data[key])
-
end
-
end
-
-
1
def respond_to_missing?(method, *args)
-
super || @struct.respond_to?(method)
-
end
-
-
1
def method_missing(method, *args, &block)
-
return @struct.send(method) if @struct.respond_to?(method)
-
super
-
end
-
end
-
end
-
module BxBlockAppointmentManagement
-
class TimeSlotsCalculator
-
-
def calculate_time_slots(start_time, end_time, slot_duration)
-
total_working_hours = (Time.parse(end_time).strftime("%H").to_i -
-
Time.parse(start_time).strftime("%H").to_i)
-
total_working_minutes = total_working_hours * 60
-
new_time_slots = []
-
new_start_time = start_time
-
sno = 1
-
until total_working_minutes < 1 do
-
start_time_key = "#{(Time.parse(new_start_time).strftime("%I:%M %p"))}"
-
end_time_key = "#{(Time.parse(new_start_time) + slot_duration.minute).strftime("%I:%M %p")}"
-
new_time_slots << {
-
from: start_time_key, to: end_time_key, booked_status: false, sno: "#{(sno)}"
-
}
-
new_start_time = (Time.parse(new_start_time) +
-
(slot_duration + 1).minute).strftime("%I:%M %p")
-
total_working_minutes -= slot_duration
-
sno += 1
-
end
-
new_time_slots
-
end
-
end
-
end
-
1
module BxBlockBook
-
1
class BookValidation
-
1
require 'date'
-
-
1
include ActiveModel::Validations
-
1
attr_reader :month, :year
-
# validate :custom_validate
-
# validate :check_presence_of_month_and_year_book
-
-
1
def initialize(params)
-
4
@month = params["month"]
-
4
@year = params["year"]
-
4
@images = params["images"]
-
end
-
-
# def custom_validate
-
# errors.add :month, 'Month must be present' if @month.blank?
-
# errors.add :month, 'Month name is not valid' unless (Date::MONTHNAMES.compact).include?(@month)
-
# errors.add :images, "please upload minimum 20 images and maximum 30 images" if (@images&.count < 20 || @images&.count > 30) if @images.present?
-
# end
-
-
# def check_presence_of_month_and_year_book
-
# book = BxBlockBook::Book.find_by(month: @month, year: @year)
-
# if book.present?
-
# errors.add(:message, "book is already present with this year and month")
-
# end
-
# end
-
end
-
end
-
module BxBlockCategories
-
class BuildCategories
-
class << self
-
CATEGORIES_AND_SUB_CATEGORIES_HASH = {
-
"K12" => [
-
"Pre Primary (kg)",
-
"Primary (1 to 5)",
-
"Middle (6 to 8)",
-
"Secondary (9 & 10)",
-
"Senior Secondary (11 & 12)"
-
],
-
"Higher Education" => [
-
"Accounting & Commerce",
-
"Animation",
-
"Architecture & Alanning",
-
"Arts (Fine/Visual/Performing)",
-
"Aviation",
-
"Banking, Finance & Insurance",
-
"Beauty & Fitness",
-
"Business & Management Studies",
-
"Design",
-
"Engineering",
-
"Hospitality & Travel",
-
"Humanities & Social Sciences",
-
"IT & Software",
-
"Law",
-
"Mass Communication & Media",
-
"Medicine & Health Sciences",
-
"Nursing",
-
"Science",
-
"Teaching & Education",
-
],
-
"Govt Job" => [
-
"Banking",
-
"Railways",
-
"Defense",
-
"Police",
-
"UGC NET",
-
"Teaching",
-
"SSC",
-
"UPSC",
-
"State PSCs",
-
"Judiciary"
-
],
-
"Competitive Exams" => [
-
"JEE",
-
"NEET",
-
"CLAT"
-
],
-
"Upskilling" => []
-
}
-
-
-
def call(categories_and_sub_categories = CATEGORIES_AND_SUB_CATEGORIES_HASH)
-
categories_and_sub_categories.each do |key,value|
-
category = BxBlockCategories::Category.where(
-
'lower(name) = ?', key.downcase
-
).first_or_create(:name=>key, :identifier=>category_identifier_hash[key])
-
category.update(identifier: category_identifier_hash[key])
-
value.each do |val|
-
category.sub_categories.where(
-
'lower(name) = ?', val.downcase
-
).first_or_create(:name=>val, categories: [category])
-
end
-
end
-
end
-
-
private
-
-
def category_identifier_hash
-
{
-
"K12" => "k12",
-
"Higher Education" => "higher_education",
-
"Govt Job" => "govt_job",
-
"Competitive Exams" => "competitive_exams",
-
"Upskilling" => "upskilling"
-
}
-
end
-
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class AudioPodcastService
-
class << self
-
-
def create_content(row, content_params, parent=nil)
-
content_exist = BxBlockContentManagement::Content.find_by(id: row[:id])
-
if content_exist
-
content_exist.update(audio_podcast_params(row, content_params))
-
return content_exist
-
else
-
content = BxBlockContentManagement::Content.new(audio_podcast_params(row, content_params))
-
content.save
-
-
if content.errors.present?
-
if parent.present?
-
parent.add_errors(content.errors.full_messages.to_sentence, row[:heading], row[:sn], 'content', 'heading')
-
else
-
return {errors: content.errors.full_messages.to_sentence}
-
end
-
end
-
return content
-
end
-
end
-
-
private
-
-
def audio_podcast_params(row, content_params)
-
content_params = content_params.merge(
-
publish_date: row[:publish_date],
-
feature_article: row[:feature_article],
-
feature_video: row[:feature_video],
-
contentable_attributes: {heading: row[:heading], description: row[:description]}
-
)
-
if row[:image_attributes].present? and row[:image_attributes][:image].present?
-
content_params[:contentable_attributes][:image_attributes] = row[:image_attributes]&.to_unsafe_hash
-
end
-
if row[:audio_attributes].present? and row[:audio_attributes][:audio].present?
-
content_params[:contentable_attributes][:audio_attributes] = row[:audio_attributes]&.to_unsafe_hash
-
end
-
content_params
-
end
-
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class BaseError < StandardError; end
-
class InvalidSheetHeaders < BaseError; end
-
-
module Base
-
extend BxBlockContentManagement::Interface
-
-
need_to_implement :import_data, :get_headers
-
-
def call(xlsx, sheet_name, error_tracker)
-
return unless xlsx.sheets.include?(sheet_name)
-
sheet = xlsx.sheet(sheet_name)
-
@sheet_headers = sheet.first
-
@sheet_content = []
-
@sheet_name = sheet_name
-
@error_tracker = error_tracker
-
-
begin
-
validate_headers!
-
process_sheet_content(sheet)
-
import_data
-
rescue BaseError => e
-
add_errors_to_tracker(e.message)
-
end
-
end
-
-
def add_errors(msg, name, sn, object_name, identifier)
-
@error_tracker.add_errors(
-
"In #{@sheet_name}: Their was error occurred in saving #{object_name} with #{identifier} " \
-
"'#{name}' in row with sn: '#{sn}', errors: #{msg}"
-
)
-
end
-
-
def add_errors_to_tracker(msg)
-
@error_tracker.add_errors(msg)
-
end
-
-
def strip(str)
-
str.to_s.strip
-
end
-
-
def strip_downcase(str)
-
strip(str).downcase
-
end
-
-
def validate_headers!
-
unless verify_headers?
-
raise InvalidSheetHeaders.new(get_missing_header_message)
-
end
-
end
-
-
def process_sheet_content(sheet)
-
sheet.each(get_headers) do |row|
-
@sheet_content << row
-
end
-
@sheet_content.shift
-
end
-
-
def verify_headers?
-
missing_headers.blank?
-
end
-
-
def missing_headers
-
get_headers.values - @sheet_headers
-
end
-
-
def build_attributes(row, trnsf_keys = transform_keys)
-
attributes = {}
-
get_headers.each do |k,_|
-
value = row[k]
-
key = trnsf_keys[k] || k
-
if value.is_a?(String)
-
attributes[key] = strip(value)
-
else
-
attributes[key] = value
-
end
-
end
-
attributes
-
end
-
-
def transform_keys
-
{}
-
end
-
-
def get_missing_header_message
-
missing_sheet_headers = missing_headers.to_sentence
-
"Missing headers in sheet #{@sheet_name}: #{missing_sheet_headers}"
-
end
-
end
-
end
-
module BxBlockContentManagement
-
module BuildContentType
-
class << self
-
-
def call(content_types = content_types_array)
-
content_types.each do |content_type|
-
BxBlockContentManagement::ContentType.where('lower(name) = ?', content_type[:name].downcase)
-
.or(BxBlockContentManagement::ContentType.where(identifier: content_type[:identifier]))
-
.first_or_create(content_type)
-
end
-
end
-
-
private
-
-
def content_types_array
-
[
-
{name: "News Articles", type: "Text", identifier: "news_article"},
-
{name: "Blogs", type: "Text", identifier: "blog"},
-
{name: "Videos (short)", type: "Videos", identifier: "video_short"},
-
{name: "Videos (full length)", type: "Videos", identifier: "video_full"},
-
{name: "Live Streaming", type: "Live Stream", identifier: "live_streaming"},
-
{name: "Audio Podcast", type: "AudioPodcast", identifier: "audio_podcast"},
-
{name: "Quiz (No analytics)", type: "Test", identifier: "quiz"},
-
{name: "Assessment (with analytics)", type: "Test", identifier: "assessment"},
-
{name: "Study Materials (PDFs/ PPTs/ Word)", type: "Epub", identifier: "study_material"}
-
]
-
end
-
-
end
-
end
-
end
-
module BxBlockContentManagement
-
module BuildRole
-
class << self
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class BulkDataImportService
-
def store_data(xlsx, current_user_id)
-
error_tracker = ErrorTracker.new
-
-
BxBlockContentManagement::CategoryImportService.call(xlsx, error_tracker)
-
BxBlockContentManagement::SubCategoryImportService.call(xlsx, error_tracker)
-
BxBlockContentManagement::ContentImportService.call(xlsx, error_tracker, current_user_id)
-
BxBlockContentManagement::PartnerImportService.call(xlsx, error_tracker)
-
-
if error_tracker.success?
-
return {success: true}
-
else
-
return {success: false, errors: error_tracker.get_errors}
-
end
-
end
-
end
-
end
-
require 'roo'
-
-
module BxBlockContentManagement
-
class BulkUploadService
-
class << self
-
-
def store_data(file_obj_path, current_user_id)
-
xlsx = Roo::Spreadsheet.open(file_obj_path)
-
sheets_name_arr = xlsx.sheets
-
ActiveRecord::Base.transaction do
-
@response = BxBlockContentManagement::BulkDataImportService.new.store_data(xlsx, current_user_id)
-
unless @response[:success]
-
@response
-
raise ActiveRecord::Rollback
-
end
-
end
-
return @response
-
end
-
end
-
end
-
end
-
# BxBlockContentManagement::CategoryImportService.call(xlsx, error_tracker)
-
-
module BxBlockContentManagement
-
class CategoryImportService
-
extend Base
-
-
class << self
-
-
def call(xlsx, error_tracker)
-
super(xlsx, 'category_sheet', error_tracker)
-
end
-
-
def import_data
-
@sheet_content.each do |sheet_content|
-
# Find or Create category
-
category = BxBlockCategories::Category.where("lower(name) = ? ", strip_downcase(sheet_content[:name])).first
-
if category.present?
-
category.rank = sheet_content[:rank]
-
else
-
category = BxBlockCategories::Category.new(category_params(sheet_content[:name], sheet_content[:rank]))
-
end
-
-
category.save
-
if category.errors.present?
-
add_errors(
-
category.errors.full_messages.to_sentence,
-
sheet_content[:name], sheet_content[:sn], 'category', 'name'
-
)
-
end
-
end
-
end
-
-
def get_headers
-
{
-
sn: 'sn',
-
name: 'name',
-
rank: 'rank'
-
}
-
end
-
-
private
-
-
def category_params(name, rank)
-
{
-
name: strip_downcase(name),
-
rank: rank
-
}
-
end
-
-
end
-
end
-
end
-
# BxBlockContentManagement::CategoryImportService.call(xlsx, error_tracker)
-
-
module BxBlockContentManagement
-
class ContentImportService
-
extend Base
-
-
class << self
-
-
def call(xlsx, error_tracker, current_user_id)
-
@current_user_id = current_user_id
-
super(xlsx, 'content_sheet', error_tracker)
-
end
-
-
def import_data
-
@sheet_content.each do |sheet_content|
-
build_value = build_attributes(sheet_content)
-
-
category = BxBlockCategories::Category.find_by('lower(name) = ?', strip_downcase(build_value[:category_name]))
-
unless category.present?
-
add_errors(
-
"can't find category with this name '#{build_value[:category_name]}'",
-
sheet_content[:heading], sheet_content[:sn], 'content', 'heading'
-
)
-
end
-
-
sub_category = BxBlockCategories::SubCategory.find_by(
-
'lower(name) = ?', strip_downcase(build_value[:sub_category_name])
-
)
-
unless sub_category.present?
-
add_errors(
-
"can't find sub category with this name '#{build_value[:sub_category_name]}'",
-
sheet_content[:heading], sheet_content[:sn], 'content', 'heading'
-
)
-
end
-
-
content_type = BxBlockContentManagement::ContentType.find_by(
-
'lower(name) = ?', strip_downcase(build_value[:content_type_name])
-
)
-
unless content_type.present?
-
add_errors(
-
"can't find content type with this name '#{build_value[:content_type]}'",
-
sheet_content[:heading], sheet_content[:sn], 'content', 'heading'
-
)
-
end
-
-
language = BxBlockLanguageOptions::Language.find_by(
-
'lower(name) = ?', strip_downcase(build_value[:language])
-
)
-
unless language.present?
-
add_errors(
-
"can't find language with this name '#{build_value[:category_name]}'",
-
sheet_content[:heading], sheet_content[:sn], 'content', 'heading'
-
)
-
end
-
-
tags = build_value[:tags]&.split(",")
-
-
if category.present? && sub_category.present? && content_type.present? && language.present?
-
BxBlockContentManagement::CreateContentService.create_content(
-
content_type, sheet_content, sub_category, language, category, tags, @current_user_id, self
-
)
-
end
-
end
-
end
-
-
def get_headers
-
{
-
sn: 'sn',
-
id: 'id',
-
category_name: 'category_name',
-
sub_category_name: 'sub_category_name',
-
tags: 'tags',
-
searchable_text: 'searchable_text',
-
publish_date: 'publish_date',
-
status: 'status',
-
language: 'language',
-
content_type_name: "content_type_name",
-
author_id: "author_id",
-
heading: "heading",
-
description: "description",
-
affiliation: "affiliation",
-
separate_section: "separate_section",
-
hyperlink: "hyperlink"
-
}
-
end
-
end
-
end
-
end
-
# BxBlockContentManagement::CategoryImportService.call(xlsx, error_tracker)
-
-
module BxBlockContentManagement
-
class CreateContentService
-
-
class << self
-
-
def create_content(content_type, sheet_content, sub_category, language, category, tags, parent_error_tracker=nil)
-
case content_type.type
-
when "Text"
-
BxBlockContentManagement::TextService.create_content(
-
sheet_content,
-
create_content_params(
-
sheet_content,
-
sub_category.id,
-
language.id,
-
category.id,
-
content_type.id,
-
tags
-
),
-
content_type.identifier,
-
parent_error_tracker
-
)
-
when "Videos"
-
BxBlockContentManagement::VideoService.create_content(
-
sheet_content,
-
create_content_params(
-
sheet_content,
-
sub_category.id,
-
language.id,
-
category.id,
-
content_type.id,
-
tags
-
),
-
parent_error_tracker)
-
when "Live Stream"
-
BxBlockContentManagement::LiveStreamService.create_content(
-
sheet_content,
-
create_content_params(
-
sheet_content,
-
sub_category.id,
-
language.id,
-
category.id,
-
content_type.id,
-
tags
-
),
-
parent_error_tracker
-
)
-
when "AudioPodcast"
-
BxBlockContentManagement::AudioPodcastService.create_content(
-
sheet_content,
-
create_content_params(
-
sheet_content,
-
sub_category.id,
-
language.id,
-
category.id,
-
content_type.id,
-
tags
-
),
-
parent_error_tracker
-
)
-
when "Test"
-
BxBlockContentManagement::TestService.create_content(
-
sheet_content,
-
create_content_params(
-
sheet_content,
-
sub_category.id,
-
language.id,
-
category.id,
-
content_type.id,
-
tags
-
),
-
parent_error_tracker
-
)
-
when "Epub"
-
BxBlockContentManagement::EpubService.create_content(
-
sheet_content,
-
create_content_params(
-
sheet_content,
-
sub_category.id,
-
language.id,
-
category.id,
-
content_type.id,
-
tags
-
),
-
parent_error_tracker
-
)
-
end
-
end
-
-
private
-
-
def create_content_params(content, sub_category_id, language_id, category_id, content_type_id, tags)
-
{
-
category_id: category_id,
-
sub_category_id: sub_category_id,
-
language_id: language_id,
-
searchable_text: content[:searchable_text],
-
content_type_id: content_type_id,
-
status: content[:status],
-
tag_list: tags
-
}
-
end
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class EpubService
-
class << self
-
-
def create_content(row, content_params, parent_error_tracker=nil)
-
content_exist = BxBlockContentManagement::Content.find_by(id: row[:id])
-
if content_exist
-
content_exist.update(epub_params(row, content_params))
-
return content_exist
-
else
-
content = BxBlockContentManagement::Content.new(epub_params(row, content_params))
-
content.save
-
if content.errors.present?
-
if parent_error_tracker.present?
-
parent_error_tracker.add_errors(
-
content.errors.full_messages.to_sentence, row[:heading], row[:sn], 'content', 'heading'
-
)
-
else
-
return {errors: content.errors.full_messages.to_sentence}
-
end
-
end
-
return content
-
end
-
end
-
-
private
-
-
def epub_params(row, content_params)
-
content_params = content_params.merge(
-
publish_date: row[:publish_date],
-
feature_article: row[:feature_article],
-
feature_video: row[:feature_video],
-
contentable_attributes: { heading: row[:heading], description: row[:description] }
-
)
-
if row[:pdfs_attributes].present?
-
content_params[:contentable_attributes][:pdfs_attributes] = row[:pdfs_attributes]&.to_unsafe_hash
-
end
-
content_params
-
end
-
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class ErrorTracker
-
def initialize
-
@errors = []
-
end
-
-
def add_errors(errors)
-
@errors.push(*errors)
-
end
-
-
def error?
-
@errors.any?
-
end
-
-
def success?
-
!error?
-
end
-
-
def get_errors
-
@errors
-
end
-
end
-
end
-
module BxBlockContentManagement
-
module Interface
-
def need_to_implement(*method_names)
-
method_names.each do |method_name|
-
define_method(method_name) { |*args|
-
raise "Not implemented #{method_name}, please add method to your module."
-
}
-
end
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class LiveStreamService
-
class << self
-
-
def create_content(row, content_params, parent_error_tracker=nil)
-
content_exist = BxBlockContentManagement::Content.find_by(id: row[:id])
-
-
if content_exist
-
content_exist.update(live_stream_params(row, content_params))
-
return content_exist
-
else
-
content = BxBlockContentManagement::Content.new(live_stream_params(row, content_params))
-
content.save
-
if content.errors.present?
-
if parent_error_tracker.present?
-
error_tracker.add_errors(
-
content.errors.full_messages.to_sentence, row[:heading], row[:sn], 'content', 'heading'
-
)
-
else
-
return {errors: content.errors.full_messages.to_sentence}
-
end
-
end
-
return content
-
end
-
end
-
-
private
-
-
def live_stream_params(row, content_params)
-
content_params.merge(
-
publish_date: row[:publish_date],
-
feature_article: row[:feature_article],
-
feature_video: row[:feature_video],
-
contentable_attributes: {
-
headline: row[:heading] || row[:headline],
-
description: row[:description],
-
comment_section: row[:separate_section] || row[:comment_section]
-
}
-
)
-
end
-
-
end
-
end
-
end
-
# BxBlockContentManagement::CategoryImportService.call(xlsx, error_tracker)
-
-
module BxBlockContentManagement
-
class PartnerImportService
-
extend Base
-
-
class << self
-
-
def call(xlsx, error_tracker)
-
super(xlsx, 'partner_sheet', error_tracker)
-
end
-
-
def import_data
-
-
@sheet_content.each do |sheet_content|
-
-
build_value = build_attributes(sheet_content)
-
category_arr = []
-
build_value[:categories_name].split(", ").each do |category_name|
-
category = BxBlockCategories::Category.find_by('lower(name) = ?', strip_downcase(category_name))
-
unless category.present?
-
add_errors(
-
"can't find category with this name",
-
sheet_content[:name], sheet_content[:sn], 'partner', 'name'
-
)
-
else
-
category_arr << category.id
-
end
-
end
-
-
sub_category_arr = []
-
-
build_value[:sub_categories_name].split(", ").each do |sub_category_name|
-
sub_category = BxBlockCategories::SubCategory.find_by(
-
'lower(name) = ?', strip_downcase(sub_category_name)
-
)
-
unless sub_category.present?
-
add_errors(
-
"can't find sub category with this name",
-
sheet_content[:name], sheet_content[:sn], 'partner', 'name'
-
)
-
else
-
sub_category_arr << sub_category.id
-
end
-
end
-
-
content_type_arr = []
-
-
build_value[:content_types_name].split(", ").each do |content_type_name|
-
content_type = BxBlockContentManagement::ContentType.find_by(
-
'lower(name) = ?', strip_downcase(content_type_name)
-
)
-
unless content_type.present?
-
add_errors(
-
"can't find content type with this name",
-
sheet_content[:name], sheet_content[:sn], 'partner', 'name'
-
)
-
else
-
content_type_arr << content_type.id
-
end
-
end
-
end
-
end
-
-
def get_headers
-
{
-
sn: 'sn',
-
email: 'email',
-
name: 'name',
-
spoc_name: 'spoc_name',
-
address: 'address',
-
categories_name: 'categories_name',
-
sub_categories_name: 'sub_categories_name',
-
content_types_name: 'content_types_name',
-
spoc_contact: 'spoc_contact',
-
status: 'status',
-
partner_type: 'partner_type',
-
partnership_type: 'partnership_type',
-
partner_margins_per: 'partner_margins_per',
-
tax_margins: 'tax_margins',
-
bank_ifsc: 'bank_ifsc',
-
account_number: 'account_number',
-
account_name: 'account_name',
-
bank_name: 'bank_name'
-
}
-
end
-
-
private
-
-
def create_admin_attributes(name, email, spoc_name, role, address, spoc_contact, status,
-
partner_type, partnership_type, partner_margins_per, tax_margins,
-
bank_ifsc, account_number, account_name, bank_name, category_ids,
-
sub_category_ids, content_type_ids)
-
{
-
email: email,
-
role: role,
-
partner_attributes:{
-
name: name,
-
address: address,
-
spoc_name: spoc_name,
-
spoc_contact: spoc_contact,
-
category_ids: category_ids,
-
sub_category_ids: sub_category_ids,
-
content_type_ids: content_type_ids,
-
status: status,
-
partner_type: partner_type,
-
partnership_type: partnership_type,
-
partner_margins_per: partner_margins_per,
-
tax_margins: tax_margins,
-
bank_ifsc: bank_ifsc,
-
account_number: account_number,
-
account_name: account_name,
-
bank_name: bank_name
-
}
-
}
-
end
-
-
end
-
end
-
end
-
# BxBlockContentManagement::CategoryImportService.call(xlsx, error_tracker)
-
-
module BxBlockContentManagement
-
class SubCategoryImportService
-
extend Base
-
-
class << self
-
-
def call(xlsx, error_tracker)
-
super(xlsx, 'sub_category_sheet', error_tracker)
-
end
-
-
def import_data
-
-
@sheet_content.each do |sheet_content|
-
category_new = nil
-
parent = nil
-
# Find or Create category
-
if sheet_content[:parent_name].present?
-
parent = BxBlockCategories::SubCategory.find_by(
-
'lower(name) = ?', strip_downcase(sheet_content[:parent_name])
-
)
-
add_errors(
-
"can't find parent with name '#{sheet_content[:parent_name]}'",
-
sheet_content[:name], sheet_content[:sn], 'sub category', 'name'
-
) unless parent.present?
-
end
-
if sheet_content[:category_name].present?
-
category_new = find_category(sheet_content[:category_name])
-
unless category_new.present?
-
add_errors(
-
"can't find category with name '#{sheet_content[:parent_name]}'",
-
sheet_content[:name], sheet_content[:sn], 'sub category', 'name'
-
)
-
else
-
sub_category = create_sub_category(sheet_content[:name], category_new, parent)
-
if sub_category.errors.present?
-
add_errors(
-
sub_category.errors.full_messages.to_sentence,
-
sheet_content[:name], sheet_content[:sn], 'sub category', 'name'
-
)
-
end
-
end
-
else
-
sub_category = create_sub_category(sheet_content[:name], category_new, parent)
-
if sub_category.errors.present?
-
add_errors(
-
sub_category.errors.full_messages.to_sentence,
-
sheet_content[:name], sheet_content[:sn], 'sub category', 'name'
-
)
-
end
-
end
-
end
-
end
-
-
def get_headers
-
{
-
sn: 'sn',
-
name: 'name',
-
category_name: 'category_name',
-
parent_name: 'parent_name',
-
rank: 'rank'
-
}
-
end
-
-
private
-
-
def find_category(c_name)
-
BxBlockCategories::Category.find_by('lower(name) = ?', strip_downcase(c_name))
-
end
-
-
def create_sub_category(sc_name, category=nil, parent=nil)
-
sub_category_exist = BxBlockCategories::SubCategory.find_by('lower(name) = ?', strip_downcase(sc_name))
-
if sub_category_exist.blank?
-
sub_category_exist = BxBlockCategories::SubCategory.new()
-
end
-
sub_category_exist.update(sub_category_params(sc_name, parent, category))
-
sub_category_exist
-
end
-
-
def sub_category_params(sc_name, parent, category=nil)
-
-
params = {
-
name: sc_name,
-
parent_id: parent&.id
-
}
-
params.merge!(categories: [category]) if category.present?
-
params
-
end
-
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class TestService
-
class << self
-
-
def create_content(row, content_params, parent_error_tracker=nil)
-
content_exist = BxBlockContentManagement::Content.find_by(id: row[:id])
-
if content_exist
-
content_exist.update(test_params(row, content_params))
-
return content_exist
-
else
-
content = BxBlockContentManagement::Content.new(test_params(row, content_params))
-
content.save
-
if content.errors.present?
-
if parent_error_tracker.present?
-
parent_error_tracker.add_errors(
-
content.errors.full_messages.to_sentence, row[:heading], row[:sn], 'content', 'heading'
-
)
-
else
-
return {errors: content.errors.full_messages.to_sentence}
-
end
-
end
-
return content
-
end
-
end
-
-
private
-
-
def test_params(row, content_params)
-
content_params.merge(
-
publish_date: row[:publish_date],
-
feature_article: row[:feature_article],
-
feature_video: row[:feature_video],
-
contentable_attributes: { headline: row[:heading] || row[:headline], description: row[:description] }
-
)
-
end
-
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class TextService
-
class << self
-
def create_content(row, content_params, identifier, parent_error_tracker=nil)
-
content_exist = BxBlockContentManagement::Content.find_by(id: row[:id])
-
if content_exist
-
if content_exist.content_type.identifier == 'blog'
-
parent_error_tracker.present? ? save_with_author(row, parent_error_tracker) : save_with_author(row)
-
content_exist.update(text_content_params(row, content_params).merge(author_id: row[:author_id]))
-
else
-
content_exist.update(text_content_params(row, content_params))
-
end
-
return content_exist
-
else
-
if identifier == 'blog'
-
save_with_author(row, parent_error_tracker)
-
content = BxBlockContentManagement::Content.new(
-
text_content_params(row, content_params
-
).merge(author_id: row[:author_id]))
-
content.save
-
else
-
content = BxBlockContentManagement::Content.new(text_content_params(row, content_params))
-
content.save
-
end
-
-
if content.errors.present?
-
if parent_error_tracker.present?
-
parent_error_tracker.add_errors(
-
content.errors.full_messages.to_sentence, row[:heading], row[:sn], 'content', 'heading'
-
)
-
else
-
return {errors: content.errors.full_messages.to_sentence}
-
end
-
end
-
return content
-
end
-
end
-
-
private
-
-
def text_content_params(row, content_params)
-
content_params = content_params.merge(
-
publish_date: row[:publish_date],
-
feature_article: row[:feature_article],
-
feature_video: row[:feature_video],
-
contentable_attributes: {
-
headline: row[:heading] || row[:headline],
-
content: row[:description] || row[:content],
-
hyperlink: row[:hyperlink],
-
affiliation: row[:affiliation]
-
}
-
)
-
if row[:images_attributes].present?
-
content_params[:contentable_attributes][:images_attributes] = row[:images_attributes]&.to_unsafe_hash
-
end
-
if row[:videos_attributes].present?
-
content_params[:contentable_attributes][:videos_attributes] = row[:videos_attributes]&.to_unsafe_hash
-
end
-
content_params
-
end
-
-
def save_with_author(row, parent_error_tracker=nil)
-
@author = BxBlockContentManagement::Author.find_by(id: row[:author_id])
-
(parent_error_tracker ? parent_error_tracker.add_errors(
-
"author not find with id '#{row[:author_id]}'",
-
row[:heading],
-
row[:sn],
-
'content',
-
'heading'
-
) : (return {errors: "author not find"})
-
) unless @author.present?
-
end
-
-
end
-
end
-
end
-
module BxBlockContentManagement
-
class VideoService
-
class << self
-
-
def create_content(row, content_params, parent_error_tracker=nil)
-
content_exist = BxBlockContentManagement::Content.find_by(id: row[:id])
-
if content_exist
-
content_exist.update(video_content_params(row, content_params))
-
return content_exist
-
else
-
content = BxBlockContentManagement::Content.new(video_content_params(row, content_params))
-
content.save
-
if content.errors.present?
-
if parent_error_tracker
-
parent_error_tracker.add_errors(
-
content.errors.full_messages.to_sentence, row[:heading], row[:sn], 'content', 'heading'
-
)
-
else
-
return {errors: content.errors.full_messages.to_sentence}
-
end
-
end
-
return content
-
end
-
end
-
-
private
-
-
def video_content_params(row, content_params)
-
content_params = content_params.merge(
-
publish_date: row[:publish_date],
-
feature_article: row[:feature_article],
-
feature_video: row[:feature_video],
-
contentable_attributes: {
-
headline: row[:heading] || row[:headline],
-
description: row[:description],
-
separate_section: row[:separate_section]
-
}
-
)
-
if row[:image_attributes].present?
-
content_params[:contentable_attributes][:image_attributes] = row[:image_attributes]&.to_unsafe_hash
-
end
-
if row[:video_attributes].present?
-
content_params[:contentable_attributes][:video_attributes] = row[:video_attributes]&.to_unsafe_hash
-
end
-
content_params
-
end
-
end
-
end
-
end
-
module BxBlockCoupons
-
class CouponApplicabilityValidator < BuilderBase::BaseSerializer
-
include ActiveModel::Validations
-
-
attr_accessor(*[
-
:account,
-
:name,
-
:order_amount,
-
])
-
-
validates :name, presence: {message: 'Enter a coupon please'}
-
validate :coupon
-
validate :validate_min_order_amount
-
-
def initialize(account_id, name, order_amount)
-
@account_id = account_id
-
@name = name
-
@order_amount = order_amount
-
end
-
-
def coupon
-
return @order_coupon if defined?(@order_coupon)
-
@order_coupon = BxBlockCoupons::Coupon.find_by_name(@name)
-
return errors.add(:base, 'Invalid coupon') unless @order_coupon.present?
-
@order_coupon
-
end
-
-
private
-
-
def validate_min_order_amount
-
@coupon = coupon
-
return unless @coupon.present?
-
errors.add(
-
:min_order,
-
"Add equal or greater #{@coupon.min_order - order_amount} service to apply this coupon "
-
) unless @coupon.min_order <= order_amount.to_f
-
end
-
end
-
end
-
module BxBlockEmailNotifications
-
class SendEmailNotificationService
-
def initialize(notification)
-
@notification = notification
-
end
-
-
def call
-
email_notification = EmailNotification.create!(
-
notification: @notification,
-
send_to_email: @notification.account.email
-
)
-
EmailNotificationMailer.with(email_notification: email_notification)
-
.notification_email.deliver_later
-
-
email_notification
-
end
-
end
-
end
-
module BxBlockFedexIntegration
-
class ShipmentAttributesCreation
-
-
attr_accessor :order, :user, :hyperpay, :shipping_address
-
-
def initialize order, hyperpay
-
@order = order
-
@user = order.account
-
@hyperpay = hyperpay
-
@shipping_address = order.delivery_addresses.delivery_add.first
-
end
-
-
def call
-
{
-
"shipments_attributes": [{
-
"full_truck": false,
-
"load_description": "Dummy load description",
-
"cod_value_attributes": {
-
"amount": order.source == 'cod' ? order.total : nil,
-
"currency": hyperpay.present? ? hyperpay['data']['currency'] : nil
-
},
-
"shipment_value_attributes": {
-
"amount": order.source == 'online' ? order.total : nil,
-
"currency": hyperpay.present? ? hyperpay['data']['currency'] : nil
-
},
-
"delivery_attributes": {
-
"address": shipping_address.address,
-
"city": shipping_address.city,
-
"country": shipping_address.country,
-
"email": user.email,
-
"name": "#{user.first_name} #{user.last_name}",
-
"phone": user.phone_number,
-
"instructions": "delivery instructions",
-
"arrival_window_attributes": {
-
"begin_at": Time.current,
-
"end_at": Time.current + 7.days
-
},
-
"coordinate_attributes": {
-
"latitude": shipping_address.latitude,
-
"longitude": shipping_address.longitude
-
}
-
},
-
"pickup_attributes": {
-
"address": "18, Vijay Nagar, Indore",
-
"city": "Indore",
-
"country": "India",
-
"email": "pickup.demo@mailinator.com",
-
"name": "Pickup user",
-
"phone": "1234567891",
-
"instructions": "pickup instructions",
-
"arrival_window_attributes": {
-
"begin_at": "2020-10-09 07:13:07 UTC",
-
"end_at": "2020-10-15 07:13:07 UTC"
-
},
-
"coordinate_attributes": {
-
"latitude": "22.759146",
-
"longitude": "75.891044"
-
}
-
},
-
"items_attributes": [
-
{
-
"weight": total_weight,
-
"quantity": order_quantity,
-
"stackable": true,
-
"item_type": "PALLET",
-
"dimension_attributes": {
-
"height": 1,
-
"length": 10,
-
"width": 10
-
}
-
}
-
]
-
}]
-
}
-
end
-
-
def total_weight
-
BxBlockCatalogue::Catalogue.joins(
-
"LEFT JOIN order_items ON order_items.catalogue_id = catalogues.id"
-
).where(
-
id: order.order_items.pluck(:catalogue_id)
-
).group("catalogues.id").sum(&:weight).to_f
-
end
-
-
def order_quantity
-
order.order_items.group('order_items.id').sum(&:quantity).to_i
-
end
-
-
end
-
end
-
module BxBlockFedexIntegration
-
class ShipmentService
-
require 'oauth2'
-
require 'json'
-
-
OAUTH_SITE_URL = "https://auth-dev.525k.io".freeze
-
BASE_URL = "https://api-dev.scdev.io/api".freeze
-
CLIENT_ID = ENV['_525K_CLIENT_ID'].freeze
-
CLIENT_SECRET = ENV['_525K_CLIENT_SECRET'].freeze
-
API_KEY = ENV['_525K_API_KEY'].freeze
-
# CLIENT_ID = 'eoranfipd3srt30dodu12mjiq'.freeze
-
# CLIENT_SECRET = 'pjrvsoolgut284rqkf7ori8c2m0jdocibvi9ta3lqd9cdkarpbh'.freeze
-
# API_KEY = 'Rtjh3tWpoFaDNyFOIygHm4Qz8In7neO8r31r7795'.freeze
-
-
-
attr_reader :token
-
-
def initialize
-
client = OAuth2::Client.new(CLIENT_ID, CLIENT_SECRET, :site => OAUTH_SITE_URL)
-
client.options[:authorize_url] = "/oauth2/authorize"
-
client.options[:token_url] = "/oauth2/token"
-
-
@token = client.client_credentials.get_token
-
end
-
-
def create(shipment_params)
-
create_shipment = CreateShipment.new(shipment_params)
-
-
payload = trasformed_payload(create_shipment)
-
response = token.post("#{BASE_URL}/shipments", body: payload.to_json, headers: headers)
-
result = JSON.parse response.body
-
-
if result['shipments'].present?
-
result = result['shipments'][0]
-
save_create_shipment(create_shipment, result)
-
end
-
-
result
-
end
-
-
def get(waybill)
-
response = token.get("#{BASE_URL}/shipments/#{waybill}", headers: headers)
-
JSON.parse response.body
-
end
-
-
private
-
-
def headers
-
{"Content-Type":"application/json", "x-api-key": API_KEY}
-
end
-
-
def trasformed_payload(create_shipment)
-
serialized_data = CreateShipmentSerializer.new(create_shipment).serializable_hash
-
data = serialized_data[:data][:attributes]
-
data.deep_transform_keys { |key| key.to_s.camelcase(:lower) }
-
end
-
-
def save_create_shipment(create_shipment, result)
-
begin
-
create_shipment.waybill = result['waybill']
-
create_shipment.save!
-
rescue ActiveRecord::RecordInvalid => e
-
puts e.message
-
end
-
end
-
end
-
end
-
module BxBlockGallery
-
class PhotoValidation
-
include ActiveModel::Validations
-
attr_reader :month, :year, :images
-
validate :custom_validate
-
validate :check_images
-
-
def initialize(params)
-
@month = params["month"]
-
@year = params["year"]
-
@images = params["images"]
-
end
-
-
def custom_validate
-
errors.add :month, 'Month must be present' if @month.blank?
-
# errors.add :images, 'Only JPEG, JPG and PNG file extensions are allowed.' unless [".jpeg", ".jpg", ".png"].include?(File.extname(@images)) if @images.present?
-
errors.add :year, 'Year must be present' if @year.blank?
-
errors.add :images, "cannot upload more than 20 images" if @images.length > 20
-
end
-
-
def check_images
-
photo_count = BxBlockGallery::Photo.find_by(year: @year, month: @month)&.images&.count
-
errors.add :message, "Already 20 images present with this year and month please select other month or year" and return if photo_count == 20
-
end
-
end
-
end
-
module BxBlockLanguageOptions
-
class BuildLanguages
-
class << self
-
-
def call(languages = languages_array)
-
languages.each do |language|
-
BxBlockLanguageOptions::Language.where(
-
'lower(name) = ?', language[:name].downcase
-
).first_or_create(name: language[:name], language_code: language[:language_code])
-
end
-
end
-
-
private
-
-
def languages_array
-
[
-
{name: "Hindi", language_code: "hi"},
-
{name: "English", language_code: "en"},
-
{name: "Telugu", language_code: "te"},
-
{name: "Tamil", language_code: "ta"},
-
{name: "Marathi", language_code: "mr"},
-
{name: "Bangla", language_code: "bn"},
-
{name: "Gujarati", language_code: "gu"},
-
{name: "Oriya", language_code: "or"}
-
]
-
end
-
-
end
-
end
-
end
-
module BxBlockLanguageOptions
-
class CreateAndUpdateTranslations
-
class << self
-
-
def call
-
translations = YAML.load_file(Rails.root.join("config", "locales/en.yml"))
-
en_translations = flatten_hash(translations["en"])
-
en_translations.each do |key, value|
-
application_message = BxBlockLanguageOptions::ApplicationMessage.find_by(name: key)
-
unless application_message.present?
-
BxBlockLanguageOptions::ApplicationMessage.create(
-
name: key, translations_attributes: [ {message: value, locale: "en"} ]
-
)
-
end
-
end
-
end
-
-
private
-
def flatten_hash(param, prefix=nil)
-
param.each_pair.reduce({}) do |a, (k, v)|
-
v.is_a?(Hash) ? a.merge(flatten_hash(v, "#{prefix}#{k}.")) : a.merge("#{prefix}#{k}" => v)
-
end
-
end
-
end
-
end
-
end
-
require 'roo'
-
-
module BxBlockLanguageOptions
-
class ImportDataService
-
class << self
-
-
def store_data(file_obj_path)
-
xlsx = Roo::Spreadsheet.open(file_obj_path)
-
sheets_name_arr = xlsx.sheets
-
unless sheets_name_arr.include?("translations_sheet")
-
return {success: false, error: "Please add translations sheet"}
-
end
-
ActiveRecord::Base.transaction do
-
@response = BxBlockLanguageOptions::TranslationDataImportService.new.store_data(xlsx)
-
unless @response[:success]
-
raise ActiveRecord::Rollback
-
end
-
end
-
return @response
-
end
-
-
end
-
end
-
end
-
module BxBlockLanguageOptions
-
class SerializeTranslations
-
class << self
-
-
def call(application_messages)
-
serialized_hash = {}
-
application_messages.find_each do |application_message|
-
serialized_hash[application_message.name] = application_message.message
-
end
-
serialized_hash
-
end
-
end
-
end
-
end
-
# BxBlockLanguageOptions::SetAvailableLocales.call
-
module BxBlockLanguageOptions
-
class SetAvailableLocales
-
class << self
-
def call
-
language_codes = [I18n.default_locale.to_s]
-
language_codes.push(
-
*BxBlockLanguageOptions::Language.pluck(:language_code).compact
-
) if BxBlockLanguageOptions::Language.table_exists? rescue false
-
I18n.available_locales = language_codes.uniq
-
end
-
end
-
end
-
end
-
module BxBlockLanguageOptions
-
class TranslationDataImportService
-
def store_data(xlsx)
-
arr = []
-
translations_data = xlsx.sheet("translations_sheet")
-
unless translations_data.count > 1
-
return {success: false, error: "No data present in translations sheet"}
-
end
-
-
success, missing_headers = validate_headers(translations_data.first)
-
unless success
-
return {success: false, error: "missing headers: #{missing_headers} in translations sheet"}
-
end
-
-
translations_data.each(headers) do |row|
-
arr << row
-
end
-
-
arr[1..].each do |arr2|
-
return {
-
success: false,
-
error: "key not present in translations sheet"
-
} unless arr2[:key].present?
-
-
return {
-
success: false,
-
error: "key -#{ arr2[:key] } serial number not present in translations sheet"
-
} unless arr2[:sn].present?
-
-
application_message = BxBlockLanguageOptions::ApplicationMessage.find_or_initialize_by(name: arr2[:key])
-
I18n.available_locales.each do |locale|
-
if application_message.id.present?
-
translation = application_message.translations.find_or_initialize_by(locale: locale.to_s)
-
translation.message = arr2[locale].to_s
-
unless translation.save
-
return {
-
success: false,
-
error: "Some error occured in Application Message data in row- #{arr2[:sn]} ->" \
-
" #{translation.errors.full_messages} "
-
}
-
end
-
else
-
application_message.translations_attributes= [{message: arr2[locale], locale: locale.to_s}]
-
end
-
unless application_message.save
-
return {
-
success: false,
-
error: "Some error occured in Application Message data in row- #{arr2[:sn]} ->" \
-
" #{application_message.errors.full_messages} "
-
}
-
end
-
end
-
end
-
return {success: true}
-
end
-
-
private
-
-
def validate_headers(sheet_headers)
-
missing_headers = headers.values - sheet_headers
-
[missing_headers.blank?, missing_headers.join(', ')]
-
end
-
-
def headers
-
available_headers = {sn: 'sn', key: 'key'}
-
BxBlockLanguageOptions::Language.pluck(:language_code).each do |language_code|
-
available_headers.merge!("#{language_code}": language_code.to_s)
-
end
-
available_headers
-
end
-
end
-
end
-
module BxBlockNotifications
-
class NotificationCreator
-
attr_accessor :created_by,
-
:headings,
-
:contents,
-
:app_url,
-
:account_id
-
def initialize(created_by, headings, contents, app_url, account_id)
-
@created_by = created_by
-
@headings = headings
-
@contents = contents
-
@app_url = app_url
-
@account_id = account_id
-
end
-
-
def call
-
@notification = BxBlockNotifications::Notification.create(
-
created_by: created_by,
-
headings: headings,
-
contents: contents,
-
app_url: app_url,
-
account_id: account_id
-
)
-
end
-
end
-
end
-
module BxBlockOrderManagement
-
class AddAddressToOrder
-
-
attr_accessor :params, :user, :order, :delivery_address, :billing_address
-
-
def initialize(params, user)
-
@params = params
-
@user = user
-
@order = Order.find_by(account_id: @user.id, id: params[:order_id])
-
end
-
-
def call
-
if params.present?
-
set_delivery_address
-
if is_address_correct? && delivery_address.save
-
DeliveryAddress.rest_addresses(delivery_address.id).where(
-
account_id: user.id
-
).update_all(is_default: false) if delivery_address.is_default
-
-
delivery_address_ids = order.delivery_addresses.where(
-
address_for: delivery_address.address_for
-
).pluck(:id)
-
-
if delivery_address_ids.present?
-
order.delivery_address_orders.address_ids(delivery_address_ids).destroy_all
-
end
-
-
if order.delivery_addresses.where(id: delivery_address.id).blank?
-
order.delivery_addresses << delivery_address
-
end
-
if billing_address.present? && billing_address.save
-
-
DeliveryAddress.rest_addresses(billing_address.id).where(
-
account_id: user.id
-
).update_all(is_default: false) if billing_address.is_default
-
-
billing_address_ids = order.delivery_addresses.where(
-
address_for: billing_address.address_for
-
).pluck(:id)
-
-
order.delivery_address_orders.address_ids(
-
billing_address_ids
-
).destroy_all if delivery_address_ids.present?
-
-
order.delivery_addresses << billing_address
-
end
-
-
return OpenStruct.new(
-
success?: true,
-
data: {},
-
msg: 'Address added successfully',
-
code: 200
-
)
-
else
-
return OpenStruct.new(
-
success?: false,
-
data: nil,
-
msg: "Ooops, Sorry it seems like your address doesn't cover store's delivery area. " \
-
"Try again with valid address",
-
code: 404
-
)
-
end
-
else
-
return OpenStruct.new(
-
success?: false,
-
data: nil,
-
msg: "Ooops, Sorry it seems like you didn't provide the delivery address.",
-
code: 404
-
)
-
end
-
end
-
-
private
-
-
def is_address_correct?
-
delivery_address.present? ? true : false
-
end
-
-
def address_params
-
params.require(:address).permit(
-
:name, :flat_no, :address, :address_line_2, :zip_code, :phone_number, :is_default,
-
:state, :country, :city, :landmark
-
)
-
end
-
-
def billing_params
-
params.require(:address).require(:billing_address).permit(
-
:name, :flat_no, :address, :address_line_2, :zip_code, :phone_number, :is_default,
-
:state, :country, :city, :landmark
-
)
-
end
-
-
def set_delivery_address
-
@delivery_address = params[:delivery_address_id] ?
-
DeliveryAddress.find_by(account_id: user.id, id: params[:delivery_address_id]) :
-
DeliveryAddress.new(address_params.merge({ account_id: user.id }))
-
@delivery_address.is_default = true if DeliveryAddress.find_by(account_id: user.id).blank?
-
if params[:billing_same_as_shipping]
-
order.delivery_address_orders.destroy_all
-
@delivery_address.address_for = "billing and shipping"
-
elsif params[:address][:billing_address].present?
-
shipping_and_billing_ids = order.delivery_addresses.billing_and_shipping.pluck(:id)
-
order.delivery_address_orders.address_ids(shipping_and_billing_ids).destroy_all
-
@delivery_address.address_for = "shipping"
-
@billing_address = DeliveryAddress.new(billing_params.merge({ account_id: user.id }))
-
@billing_address.is_default = true if DeliveryAddress.find_by(account_id: user.id).blank?
-
@billing_address.address_for = "billing"
-
end
-
end
-
-
end
-
end
-
module BxBlockOrderManagement
-
class AddProduct
-
attr_accessor :params, :quantity, :catalogue, :order, :user, :catalogue_variant
-
-
def initialize(params, user)
-
@params = params
-
@quantity = params[:quantity]
-
@catalogue_id = params[:catalogue_id]
-
@catalogue = BxBlockCatalogue::Catalogue.find(@catalogue_id)
-
@order = Order.find_by_id(params[:cart_id]) if params[:cart_id].present?
-
@order = Order.create!(
-
account_id: user.id,
-
status: "created",
-
coupon_code_id: params[:coupon_code_id]
-
) unless params[:cart_id].present?
-
@catalogue_variant = @catalogue.catalogue_variants.find_by(id: params[:catalogue_variant_id])
-
@user = user
-
end
-
-
def call
-
if params[:catalogue_variant_id].present? && catalogue_variant.blank?
-
return OpenStruct.new(
-
success?: false,
-
data: nil,
-
msg: 'Sorry, Product Variant is not found for this product',
-
code: 404
-
)
-
elsif product_not_available?
-
return OpenStruct.new(
-
success?: false,
-
data: nil,
-
msg: 'Sorry, Product is out of stock',
-
code: 404
-
)
-
elsif order.blank?
-
return OpenStruct.new(
-
success?: false,
-
data: nil,
-
msg: 'Sorry, cart is not found',
-
code: 404
-
)
-
else
-
order.order_items.create!(order_item_params)
-
msg = "Item added in cart successfully" if params[:cart_id].present?
-
msg = "Order created successfully" unless params[:cart_id].present?
-
return OpenStruct.new(success?: true, data: order, msg: msg, code: 200)
-
end
-
end
-
-
private
-
-
def product_not_available?
-
if catalogue_variant.present?
-
quantity.to_i > (@catalogue_variant.stock_qty.to_i - @catalogue_variant.block_qty.to_i || 0)
-
else
-
quantity.to_i > (@catalogue.stock_qty.to_i - @catalogue.block_qty.to_i || 0)
-
end
-
end
-
-
def order_item_params
-
params.permit(:quantity, :catalogue_id, :catalogue_variant_id)
-
end
-
-
end
-
end
-
1
module BxBlockOrderManagement
-
1
class ApplyCoupon
-
1
attr_accessor :coupon_code, :cart_value, :order
-
-
1
def initialize(order, coupon, params)
-
4
@coupon_code = coupon
-
4
@order = order
-
4
@params = params
-
end
-
-
1
def call
-
4
delivery_and_tax_extract = (@order.delivery_charges.to_f + @order.tax_charges.to_f).round(2)
-
4
total_amount = (@order.sub_total - delivery_and_tax_extract).round(2)
-
4
@delivery_charges = @order.delivery_charges
-
4
discount = coupon_code.discount_type == "percentage" ?
-
3
((total_amount * coupon_code.discount) / 100) : coupon_code.discount
-
-
4
if coupon_code.discount_type == "percentage"
-
3
if coupon_code&.discount.to_f <= coupon_code&.max_capping_limit.to_i # && coupon_code&.discount_type == "percentage"
-
total_amount = (total_amount - coupon_code.discount).to_f
-
else
-
3
total_amount = total_amount.to_f - coupon_code&.max_capping_limit.to_f
-
end
-
else
-
1
total_amount = coupon_code&.discount
-
end
-
-
4
if coupon_code.discount_type == "percentage"
-
3
if coupon_code&.discount.to_f < coupon_code&.max_capping_limit.to_i #&& coupon_code.discount_type == "percentage"
-
discount_price = discount.to_f
-
3
else coupon_code&.discount.to_f > coupon_code&.max_capping_limit.to_f #&& coupon_code.discount_type == "percentage"
-
3
discount_price = coupon_code&.max_capping_limit
-
end
-
else
-
1
discount_price = coupon_code&.discount
-
end
-
-
# discount_price = coupon_code.discount_type == "percentage" ? ( @order.amount - discount ) : ( @order.amount / 2 )
-
4
create_user_offer(@order.account, @coupon_code)
-
-
4
delivery_and_tax_charges = (@order.base_price.to_i + @order.delivery_charges.to_i + @order.additional_price.to_i - discount.to_f)
-
4
tax_charges = (delivery_and_tax_charges.to_f * 18 / 100)
-
-
4
sub_total = @order.base_price.to_i + @order.delivery_charges.to_i + @order.additional_price.to_i + tax_charges.to_f
-
4
order.update(
-
coupon_code_id: coupon_code.id,
-
applied_discount: discount.round(2),
-
4
sub_total: (sub_total - discount).round(2),
-
amount: sub_total.round(2),
-
used_discount_code: @params[:code],
-
tax_charges: tax_charges.round(2)
-
)
-
end
-
-
1
def create_user_offer(account, coupon)
-
4
user_offer = BxBlockDiscountsoffers::UserOffer.find_or_initialize_by(account_id: account.id, offer_id: coupon.id)
-
4
user_offer.use_count = user_offer.use_count + 1
-
4
user_offer.applied = true
-
4
user_offer.coupon_type = coupon.coupon_type
-
4
if user_offer.referral?
-
referred_by_user = BxBlockReferrals::ReferralUser.find_by(referral_code: coupon.code)
-
referral_user = BxBlockReferrals::ReferralUser.find_by(account_id: account.id)
-
user_offer.code = referred_by_user.referral_code
-
referred_by_user.referal_count = referred_by_user.referal_count.to_i + 1
-
referral_user.code_used = referral_user.code_used.to_i + 1
-
referred_by_user.update(referal_count: referred_by_user.referal_count)
-
referral_user.update(code_used: referral_user.code_used)
-
4
elsif user_offer.share_order_code?
-
1
user_offer.code = @params[:code]
-
else
-
3
user_offer.code = coupon.code
-
end
-
4
user_offer.save!
-
end
-
end
-
end
-
1
module BxBlockOrderManagement
-
1
class RemoveCoupon
-
1
attr_accessor :coupon_code, :cart_value, :order
-
-
1
def initialize(order, params)
-
5
@order = order
-
5
@params = params
-
end
-
-
1
def call
-
5
get_quantity = @order.quantity
-
5
coupon = BxBlockDiscountsoffers::Offer.find_by(id: @order.coupon_code_id)
-
5
if coupon.coupon_type == 'referral'
-
1
user_offer = BxBlockDiscountsoffers::UserOffer.find_by(offer_id: @order.coupon_code_id, account_id: @order.account_id, code: @params[:code])
-
4
elsif coupon.coupon_type == 'share_order_code'
-
1
user_offer = BxBlockDiscountsoffers::UserOffer.find_by(offer_id: @order.coupon_code_id, account_id: @order.account_id, code: @order.used_discount_code)
-
3
elsif coupon.coupon_type == 'normal'
-
1
normal_offer = BxBlockDiscountsoffers::UserOffer.find_by(offer_id: @order.coupon_code_id, account_id: @order.account_id, code: @order.used_discount_code)
-
2
elsif coupon.coupon_type == 'specfic_user'
-
1
normal_offer = BxBlockDiscountsoffers::UserOffer.find_by(offer_id: @order.coupon_code_id, account_id: @order.account_id, code: @order.used_discount_code)
-
else
-
1
user_offer = BxBlockDiscountsoffers::UserOffer.find_by(offer_id: @order.coupon_code_id, account_id: @order.account_id, code: coupon.code)
-
end
-
5
if user_offer
-
1
user_offer.use_count = user_offer.use_count - 1
-
1
user_offer.applied = false
-
1
user_offer.save!
-
1
referred_by_user = BxBlockReferrals::ReferralUser.find_by(referral_code: coupon.code)
-
1
referral_user = BxBlockReferrals::ReferralUser.find_by(account_id: @order.account.id)
-
1
user_offer.code = referred_by_user.referral_code
-
1
referred_by_user.referal_count = referred_by_user.referal_count.to_i - 1
-
1
referral_user.code_used = referral_user.code_used.to_i - 1
-
1
referred_by_user.update(referal_count: referred_by_user.referal_count)
-
1
referral_user.update(code_used: referral_user.code_used)
-
end
-
5
if normal_offer
-
1
normal_offer.use_count = normal_offer.use_count - 1
-
1
normal_offer.save!
-
1
@order.coupon_code_id = nil
-
1
@order.applied_discount = 0.0
-
1
@order.sub_total = @order.base_price.to_i+@order.additional_price.to_i+@order.delivery_charges.to_i
-
1
@order.tax_charges = (@order.sub_total * 18 / 100).round(2)
-
1
@order.sub_total = (@order.sub_total.to_f + @order.tax_charges.to_f).round(2)
-
1
@order.amount = @order.sub_total
-
1
@order.used_discount_code = nil
-
1
@order.quantity = get_quantity
-
1
@order.save
-
end
-
5
@order.coupon_code_id = nil
-
5
@order.applied_discount = 0.0
-
5
@order.sub_total = @order.base_price.to_i+@order.additional_price.to_i+@order.delivery_charges.to_i
-
5
@order.tax_charges = (@order.sub_total * 18 / 100).round(2)
-
5
@order.sub_total = (@order.sub_total.to_f + @order.tax_charges.to_f).round(2)
-
5
@order.amount = @order.sub_total
-
5
@order.used_discount_code = nil
-
5
@order.quantity = get_quantity
-
5
@order.save
-
end
-
-
end
-
end
-
-
require "uri"
-
require "net/http"
-
-
module BxBlockOrderManagement
-
class Shiprocket
-
attr_accessor :token
-
# shiprocket_configuration = BxBlockApiConfiguration::ApiConfiguration.find_by(configuration_type: 'shiprocket')
-
SHIP_ROCKET_BASE_URL = "https://apiv2.shiprocket.in/v1/"
-
# SHIP_ROCKET_USER_EMAIL = shiprocket_configuration&.ship_rocket_user_email
-
# SHIP_ROCKET_USER_PASSWORD = shiprocket_configuration&.ship_rocket_user_password
-
-
def authorize
-
begin
-
-
puts '=======================start authorize shiprocket================'
-
url = URI("#{SHIP_ROCKET_BASE_URL}"+"external/auth/login")
-
-
https = Net::HTTP.new(url.host, url.port);
-
https.use_ssl = true
-
-
request = Net::HTTP::Post.new(url)
-
request["Content-Type"] = "application/json"
-
-
request.body = {
-
"email"=> ENV['SHIP_ROCKET_USER_EMAIL'],
-
"password"=> ENV['SHIP_ROCKET_USER_PASSWORD']
-
}.to_json
-
-
response = https.request(request)
-
@token = JSON.parse(response.body)['token']
-
-
puts '======================= got token ================'
-
-
# Get pickup location
-
url = URI("#{SHIP_ROCKET_BASE_URL}"+"external/settings/company/pickup")
-
https = Net::HTTP.new(url.host, url.port)
-
https.use_ssl = true
-
request = Net::HTTP::Get.new(url)
-
request["Content-Type"] = "application/json"
-
request["Authorization"] = "Bearer #{@token}"
-
pickup_location_response = https.request(request)
-
Rails.logger.info '======================= got pickup location ================'
-
puts '======================= got pickup location ================'
-
@pickup_location = JSON.parse(pickup_location_response.body)['data']['shipping_address'][0]['pickup_location']
-
rescue
-
@token = nil
-
end
-
end
-
-
def post_order(order_id)
-
@order = BxBlockOrderManagement::Order.find_by(id: order_id)
-
puts "======================= fetch snaps order #{@order.id}================"
-
url = URI("#{SHIP_ROCKET_BASE_URL}"+"external/orders/create/adhoc")
-
https = Net::HTTP.new(url.host, url.port);
-
https.use_ssl = true
-
request = Net::HTTP::Post.new(url)
-
request["Content-Type"] = "application/json"
-
request["Authorization"] = "Bearer #{@token}"
-
puts "======================= fetch snaps order #{@order.id}================"
-
request.body = formated_body_data(@order)
-
puts "======================= created orders data for shiprocket ================"
-
response = https.request(request)
-
puts "======================= shiprocket order #{response.read_body} ================"
-
response.read_body
-
end
-
-
def cancel_order(order_id)
-
@order = BxBlockOrderManagement::Order.find_by(id: order_id)
-
url = URI("#{SHIP_ROCKET_BASE_URL}"+"external/orders/cancel")
-
https = Net::HTTP.new(url.host, url.port);
-
https.use_ssl = true
-
request = Net::HTTP::Post.new(url)
-
request["Content-Type"] = "application/json"
-
request["Authorization"] = "Bearer #{@token}"
-
request.body = {
-
"ids"=> [@order.ship_rocket_order_id]
-
}.to_json
-
response = https.request(request)
-
response.read_body
-
end
-
-
def get_order(order_id)
-
@order = BxBlockOrderManagement::Order.find_by(id: order_id)
-
url = URI("#{SHIP_ROCKET_BASE_URL}"+"external/orders/show/#{@order.ship_rocket_order_id}")
-
https = Net::HTTP.new(url.host, url.port);
-
https.use_ssl = true
-
request = Net::HTTP::Get.new(url)
-
request["Content-Type"] = "application/json"
-
request["Authorization"] = "Bearer #{@token}"
-
response = https.request(request)
-
response.read_body
-
end
-
-
def generate_manifest(order_id)
-
@order = BxBlockOrderManagement::Order.find_by(id: order_id)
-
url = URI("#{SHIP_ROCKET_BASE_URL}"+"external/manifests/generate/")
-
https = Net::HTTP.new(url.host, url.port);
-
https.use_ssl = true
-
request = Net::HTTP::Post.new(url)
-
request["Content-Type"] = "application/json"
-
request["Authorization"] = "Bearer #{@token}"
-
request.body = {
-
"shipment_id"=> [@order.ship_rocket_shipment_id]
-
}.to_json
-
response = https.request(request)
-
response.read_body
-
end
-
-
def print_manifest(order_id)
-
@order = BxBlockOrderManagement::Order.find_by(id: order_id)
-
url = URI("#{SHIP_ROCKET_BASE_URL}"+"external/manifests/print")
-
https = Net::HTTP.new(url.host, url.port);
-
https.use_ssl = true
-
request = Net::HTTP::Post.new(url)
-
request["Content-Type"] = "application/json"
-
request["Authorization"] = "Bearer #{@token}"
-
request.body = {
-
"order_ids"=> [@order.ship_rocket_order_id]
-
}.to_json
-
response = https.request(request)
-
response.read_body
-
end
-
-
-
def generate_label(order_id)
-
@order = BxBlockOrderManagement::Order.find_by(id: order_id)
-
url = URI("#{SHIP_ROCKET_BASE_URL}"+"external/courier/generate/label/")
-
https = Net::HTTP.new(url.host, url.port);
-
https.use_ssl = true
-
request = Net::HTTP::Post.new(url)
-
request["Content-Type"] = "application/json"
-
request["Authorization"] = "Bearer #{@token}"
-
request.body = {
-
"shipment_id"=> [@order.ship_rocket_shipment_id]
-
}.to_json
-
response = https.request(request)
-
response.read_body
-
end
-
-
def generate_invoice(order_id)
-
@order = BxBlockOrderManagement::Order.find_by(id: order_id)
-
url = URI("#{SHIP_ROCKET_BASE_URL}"+"external/orders/print/invoice/")
-
https = Net::HTTP.new(url.host, url.port);
-
https.use_ssl = true
-
request = Net::HTTP::Post.new(url)
-
request["Content-Type"] = "application/json"
-
request["Authorization"] = "Bearer #{@token}"
-
request.body = {
-
"ids"=> [@order.ship_rocket_order_id]
-
}.to_json
-
response = https.request(request)
-
response.read_body
-
end
-
-
def return_order(order_id)
-
@order = BxBlockOrderManagement::Order.find_by(id: order_id)
-
url = URI("#{SHIP_ROCKET_BASE_URL}"+"external/orders/create/return/")
-
https = Net::HTTP.new(url.host, url.port)
-
https.use_ssl = true
-
request = Net::HTTP::Post.new(url)
-
request["Content-Type"] = "application/json"
-
request["Authorization"] = "Bearer #{token}"
-
request.body = return_order_data(@order)
-
response = https.request(request)
-
response.read_body
-
end
-
-
-
def track_order(order_id)
-
@order = BxBlockOrderManagement::Order.find_by(id: order_id)
-
url = URI("#{SHIP_ROCKET_BASE_URL}"+"external/courier/track/shipment/#{@order.ship_rocket_shipment_id}")
-
https = Net::HTTP.new(url.host, url.port)
-
https.use_ssl = true
-
request = Net::HTTP::Get.new(url)
-
request["Content-Type"] = "application/json"
-
request["Authorization"] = "Bearer #{token}"
-
response = https.request(request)
-
response.read_body
-
end
-
-
private
-
-
def order_items(order)
-
items = []
-
items << {"name"=> order&.book_title || "Album Book", "sku"=>"#{order.id}-#{order.order_number}", "units"=> order.quantity.present? ? order.quantity : '',"tax"=> "18","selling_price"=> order.sub_total.to_f}
-
items
-
end
-
-
-
def formated_body_data(order)
-
@order = order
-
@delivery_address = @order.address
-
-
{"order_id" => @order.id.to_s,
-
"order_date" => @order.created_at.strftime('%Y-%m-%d %I:%M'),
-
"pickup_location" => @pickup_location,
-
"channel_id" => "Custom",
-
"billing_customer_name" => @order&.address&.full_name.to_s,
-
"billing_last_name" => @order&.address&.full_name.to_s,
-
"billing_address" => @delivery_address&.address,
-
"billing_city" => @delivery_address&.city,
-
"billing_pincode" => @delivery_address&.pincode,
-
"billing_state" => @delivery_address&.state,
-
"billing_country" => "india",
-
"billing_email" => @delivery_address&.email_address,
-
"billing_phone" => @delivery_address&.phone_number,
-
"shipping_is_billing" => true,
-
"shipping_address" => @delivery_address&.address,
-
"shipping_address_2" => @shipping_address&.address_line_2,
-
"shipping_city" => @delivery_address&.city,
-
"shipping_pincode" => @delivery_address&.pincode,
-
"shipping_country" => "india",
-
"shipping_state" => @delivery_address&.state,
-
"shipping_email" => @delivery_address&.email_address,
-
"shipping_phone" => @delivery_address&.phone_number,
-
"order_items" => order_items(@order),
-
"payment_method" => "prepaid",
-
"shipping_charges" => @order.shipping_total,
-
"total_discount" => @order.applied_discount,
-
"sub_total" => @order.sub_total.to_f + @order&.applied_discount.to_f,
-
"length" => "10",
-
"breadth" => "10",
-
"height" => "10",
-
"weight" => "10",
-
}.to_json
-
end
-
-
def return_order_data(order)
-
@order = order
-
@delivery_address = @order.address
-
-
{
-
"order_id"=>@order.ship_rocket_order_id.to_s,
-
"order_date"=>@order.created_at.strftime('%Y-%m-%d %I:%M'),
-
"channel_id"=>"Custom",
-
"pickup_customer_name"=> @order&.address&.full_name.to_s,
-
"pickup_last_name"=> @order&.address&.full_name.to_s,
-
"pickup_address"=> @delivery_address&.address,
-
"pickup_address_2"=> "assasa",
-
"pickup_city"=> @delivery_address&.city,
-
"pickup_state"=> @delivery_address&.state,
-
"pickup_country"=> "India",
-
"pickup_pincode"=> @delivery_address&.pincode,
-
"pickup_email"=> @delivery_address.email_address,
-
"pickup_phone"=> @delivery_address&.phone_number,
-
"pickup_isd_code"=> "91",
-
"shipping_customer_name"=> @order&.address&.full_name.to_s,
-
"shipping_last_name"=> @order&.address&.full_name.to_s,
-
"shipping_address"=> "Castle",
-
"shipping_address_2"=> "Bridge",
-
"shipping_city"=> "ghaziabad",
-
"shipping_country"=> "India",
-
"shipping_pincode"=> 201005,
-
"shipping_state"=> "Uttarpardesh",
-
"shipping_email"=> "kumar.abhishek@shiprocket.com",
-
"shipping_isd_code"=> "91",
-
"shipping_phone"=> 8888888888,
-
"order_items"=> order_items(@order),
-
"payment_method"=> "PREPAID",
-
"total_discount"=>@order.applied_discount,
-
"sub_total" => @order.sub_total.to_f + @order&.applied_discount.to_f,
-
"length"=> 11,
-
"breadth"=> 11,
-
"height"=> 11,
-
"weight"=> 0.5
-
}.to_json
-
end
-
-
def shipping_and_billing_same?(address)
-
address&.address_for.to_s.include?('billing_and_shipping')
-
end
-
end
-
end
-
module BxBlockOrderManagement
-
class StateProcess
-
# optional args parameter can be omitted, but if you define initialize
-
# you must accept the model instance as the first parameter to it.
-
attr_accessor :order, :aasm, :user
-
-
def initialize(order, aasm)
-
@order = order
-
@aasm = aasm
-
@user = order.order.account if order.class == OrderItem
-
@user = order.account if order.class == Order
-
end
-
-
def call
-
event_name = aasm.current_event.to_s
-
if (Order::EVENTS.include? event_name) && (order.class == Order)
-
a = aasm.to_state.to_s + '_at'
-
order.update(a => Time.current)
-
end
-
create_trackings if order.class == OrderItem
-
if OrderStatus.new_statuses.pluck(:status).include? event_name.gsub('!','')
-
status_id = OrderStatus.find_or_create_by(status: event_name.gsub('!','')).id
-
order.update(order_status_id: status_id) unless order.order_status_id == status_id
-
end
-
end
-
-
private
-
-
def create_trackings
-
tracking = Tracking.find_or_create_by(date: DateTime.current, status: aasm.to_state.to_s )
-
order.order_trackings.create(tracking_id: tracking.id)
-
end
-
-
end
-
end
-
module BxBlockOrderManagement
-
class UpdateCartValue
-
attr_accessor :order
-
-
def initialize(order, user)
-
@order = order
-
@user = user
-
end
-
-
def call
-
save_order
-
if order.coupon_code.present?
-
BxBlockOrderManagement::Validity.new(order_attributes, @user).check_cart_total
-
end
-
end
-
-
def save_order
-
update_order_total
-
update_order_sub_total
-
order.save
-
end
-
-
private
-
-
def order_attributes
-
{
-
code: order.coupon_code.code,
-
cart_id: order.id,
-
cart_value: order.sub_total,
-
existing_cart: true
-
}
-
end
-
-
def update_order_total
-
order.total = order.total_price
-
order.total_after_shipping_charge
-
order.total_after_tax_charge
-
end
-
-
def update_order_sub_total
-
order.sub_total = order.sub_total_price
-
end
-
end
-
end
-
module BxBlockOrderManagement
-
class UpdatePayment
-
include Wisper::Publisher
-
-
attr_accessor :params, :payment_status, :schedule_time, :transaction_id, :order, :user
-
-
ENTITYID = "8ac7a4c874672c64017468b0fdcf0756"
-
-
def initialize(params, order)
-
@params = params
-
@payment_status = params[:status]
-
@schedule_time = params[:schedule_time]
-
@transaction_id = params[:transaction_id]
-
@order = order
-
@user = order.account
-
end
-
-
def call
-
hyperpay_response = broadcast(
-
:payment_hyperpay_get_status,
-
transaction_id,
-
("?entityId=#{ENTITYID}")
-
)
-
unless hyperpay_response.respond_to? :values
-
return OpenStruct.new(success?: false, msg: 'No Hyperspace integration found', code: 208)
-
end
-
-
@response = hyperpay_response.values.first
-
if payment_status == 'success'
-
proccess_after_payment
-
elsif payment_status == 'pending'
-
process_pending_order 'pending_order'
-
return OpenStruct.new(
-
success?: false, msg: I18n.t('messages.after_payments.internal_error'), code: 400
-
)
-
elsif payment_status == 'failed'
-
process_pending_order 'payment_failed'
-
return OpenStruct.new(
-
success?: false, msg: I18n.t('messages.after_payments.status_fail'), code: 400
-
)
-
else
-
return OpenStruct.new(success?: false, msg: 'Sorry, Something went wrong', code: 208)
-
end
-
end
-
-
def handle_other_model_attribtues
-
ActiveRecord::Base.transaction do
-
update_order_record
-
create_transaction
-
update_product_attributes
-
end
-
OpenStruct.new(success?: true, msg: 'All attributes updated successfully', code: 200)
-
rescue ActiveRecord::Rollback
-
OpenStruct.new(
-
success?: false, msg: I18n.t('messages.after_payments.internal_error'), code: 400
-
)
-
rescue ActiveRecord::RecordNotFound
-
OpenStruct.new(
-
success?: false, msg: I18n.t('messages.after_payments.internal_error'), code: 400
-
)
-
end
-
-
def proccess_after_payment
-
result = handle_other_model_attribtues
-
if result.success?
-
shipment_params = BxBlockFedexIntegration::ShipmentAttributesCreation.new(
-
order, @response
-
).call
-
shipment_service = BxBlockFedexIntegration::ShipmentService.new
-
result = shipment_service.create(shipment_params)
-
if result['status'] == "PROPOSED"
-
order.update!(
-
shipment_id: result['id'],
-
tracking_url: result['trackingURL'],
-
tracking_number: result['waybill']
-
)
-
order.confirm_order!
-
update_order_item_status
-
OpenStruct.new(
-
success?: true,
-
msg: I18n.t('messages.deliveries.success', deliver_by: "FedEx"),
-
code: 200
-
)
-
else
-
error = I18n.t('messages.deliveries.failed') + "Error from #{order.deliver_by} "
-
OpenStruct.new(success?: false, msg: error, code: 400)
-
end
-
OpenStruct.new(
-
success?: true,
-
msg: I18n.t('messages.deliveries.success', deliver_by: "FedEx"),
-
code: 200
-
)
-
else
-
OpenStruct.new(success?: false, msg: result.msg, code: 400)
-
end
-
end
-
-
private
-
-
def process_pending_order req_type
-
order.update!(
-
order_date: Time.current,
-
is_gift: params[:is_gift],
-
source: params[:source],
-
schedule_time: schedule_time
-
)
-
order.send("#{req_type}!")
-
create_transaction
-
end
-
-
def update_order_record
-
order.update!(
-
order_date: Time.current,
-
is_gift: params[:is_gift],
-
source: params[:source],
-
schedule_time: schedule_time
-
)
-
order.place_order!
-
end
-
-
def create_transaction
-
OrderTransaction.create!(
-
charge_id: transaction_id,
-
amount: @response['data']['amount'].to_i,
-
currency: @response['data']['currency'],
-
order_id: order.id,
-
account_id: user.id,
-
charge_status: payment_status
-
)
-
end
-
-
def update_product_attributes
-
order.order_items.each do |oi|
-
product = oi.catalogue
-
product.update_attributes(sold: (product.sold + oi.quantity))
-
status = oi.order.status
-
oi.update("#{status}_at".to_sym => oi.order.send("#{status}_at"), :status => status)
-
end
-
end
-
-
def update_order_item_status
-
order.order_items.each do |oi|
-
status = oi.order.status
-
oi.update("#{status}_at".to_sym => oi.order.send("#{status}_at"), :status => status)
-
end
-
end
-
-
end
-
end
-
module BxBlockOrderManagement
-
class Validity
-
attr_accessor :params, :coupon_code, :cart_value, :order, :user
-
-
def initialize(params, user)
-
@params = params
-
@coupon_code = BxBlockCouponCg::CouponCode.find_by_code(params[:code])
-
@order = BxBlockOrderManagement::Order.find(params[:cart_id])
-
@cart_value = params[:cart_value].to_f
-
@user = user
-
end
-
-
def check_cart_total
-
if coupon_code.min_cart_value && cart_value < coupon_code.min_cart_value
-
respond_error('min')
-
elsif coupon_code.max_cart_value && cart_value > coupon_code.max_cart_value
-
respond_error('max')
-
else
-
calculate_discount
-
end
-
end
-
-
def calculate_discount
-
discount = coupon_code.discount_type == "percentage" ?
-
((cart_value * coupon_code.discount) / 100) : coupon_code.discount
-
discount_price = (cart_value - discount)&.round(2)
-
order.update!(
-
coupon_code_id: coupon_code.id, total: discount_price, applied_discount: discount
-
)
-
return OpenStruct.new(
-
success?: true,
-
data: {
-
coupon: coupon_code,
-
actual_price: cart_value,
-
discount_type: coupon_code.discount_type,
-
cart_discount: coupon_code.discount,
-
discount_price: discount,
-
after_discount_price: discount_price
-
},
-
msg: 'Coupon applied successfully',
-
code: 200
-
)
-
end
-
-
def respond_error(value)
-
if value == 'min'
-
min_cart_error
-
else
-
max_cart_error
-
end
-
end
-
-
def min_cart_error
-
if params[:existing_cart] == true
-
remove_coupon
-
return OpenStruct.new(
-
success?: false,
-
data: nil,
-
msg: 'Your coupon has been removed due to min cart limit',
-
code: 208
-
)
-
else
-
return OpenStruct.new(
-
success?: false,
-
data: nil,
-
msg: 'Please add few more product(s) to apply this coupon',
-
code: 208
-
)
-
end
-
end
-
-
def max_cart_error
-
if params[:existing_cart] == true
-
remove_coupon
-
return OpenStruct.new(
-
success?: false,
-
data: nil,
-
msg: 'Your coupon has been removed due to max cart limit',
-
code: 208
-
)
-
else
-
return OpenStruct.new(
-
success?: false,
-
data: nil,
-
msg: 'Your cart amount is exceeding the limit value. Please check coupon desctiption',
-
code: 208
-
)
-
end
-
end
-
-
def remove_coupon
-
order.update_attributes!(coupon_id: nil, applied_discount: 0)
-
order.update_attributes!(total: order.total_price, sub_total: order.total_price)
-
end
-
-
end
-
end
-
module BxBlockPaymentRazorpay
-
class Payment
-
class << self
-
def create(amount, currency, receipt)
-
Razorpay::Order.create(amount: amount, currency: currency, receipt: receipt)
-
end
-
-
def verify(order_id, payment_id, signature)
-
payment_response = {
-
razorpay_order_id: order_id,
-
razorpay_payment_id: payment_id,
-
razorpay_signature: signature
-
}
-
-
Razorpay::Utility.verify_payment_signature(payment_response)
-
end
-
-
def capture(payment_id, capture_amount, currency = 'INR')
-
Razorpay::Payment.fetch(payment_id).capture(
-
amount: capture_amount,
-
currency: currency
-
)
-
end
-
-
def order_details(order_id)
-
Razorpay::Order.fetch(order_id)
-
end
-
end
-
end
-
end
-
module BxBlockPosts
-
class Create
-
def initialize(current_user, post_attributes)
-
@current_user = current_user
-
@post_attributes = post_attributes
-
end
-
-
def execute
-
post = @current_user.posts.new(@post_attributes)
-
post.save
-
post
-
end
-
end
-
end
-
module BxBlockPosts
-
class Update
-
def initialize(post, post_attributes)
-
@post = post
-
@post_attributes = post_attributes
-
end
-
-
def execute
-
image_attributes = @post_attributes.delete('image')
-
if image_attributes
-
decoded_data = Base64.decode64(image_attributes['data'])
-
image_attributes['io'] = StringIO.new(decoded_data)
-
@post.image = {
-
io: image_attributes['io'],
-
content_type: image_attributes['content_type'],
-
filename: image_attributes['filename']
-
}
-
end
-
@post.assign_attributes(@post_attributes)
-
@post.save
-
@post
-
end
-
end
-
end
-
module BxBlockProfile
-
class ChangeEmailValidator
-
include ActiveModel::Validations
-
-
attr_accessor(*[
-
:account,
-
:new_email,
-
])
-
-
validates :account, :presence => {:message => 'not found'}
-
validate :validate_account_type
-
validate :validate_email
-
-
def initialize(account_id, email)
-
@account_id = account_id
-
@email = email
-
end
-
-
def account
-
return @account if defined?(@account)
-
@account = AccountBlock::Account.find_by(:id => @account_id)
-
end
-
-
private
-
-
def validate_email
-
return if AccountBlock::EmailValidation.new(@email).valid?
-
errors.add :new_email, 'is not valid'
-
end
-
-
def validate_account_type
-
return unless account
-
return unless (invalid_account_types).include?(account.type)
-
errors.add :authentication, 'field cannot be edited'
-
end
-
-
def invalid_account_types
-
['AccountBlock::EmailAccount', 'EmailAccount']
-
end
-
end
-
end
-
module BxBlockProfile
-
class ChangePasswordValidator
-
include ActiveModel::Validations
-
-
attr_accessor(*[
-
:account,
-
:new_password,
-
])
-
-
validates :account, :presence => {:message => 'not found'}
-
validate :authenticated
-
validates :new_password, :format => {
-
:with => AccountBlock::PasswordValidation.regex,
-
:multiline => true,
-
}
-
-
def initialize(account_id, password, new_password)
-
@account_id = account_id
-
@password = password
-
@new_password = new_password
-
end
-
-
def account
-
return @account if defined?(@account)
-
@account = AccountBlock::Account.find_by(:id => @account_id)
-
end
-
-
private
-
-
def authenticated
-
return unless account
-
return if account.authenticate(@password)
-
errors.add :base, 'Invalid credentials'
-
end
-
end
-
end
-
module BxBlockProfile
-
class ChangePhoneValidator
-
include ActiveModel::Validations
-
-
attr_accessor(*[
-
:account,
-
:new_phone,
-
])
-
-
validates :account, :presence => {:message => 'not found'}
-
validate :validate_account_type
-
validate :validate_phone
-
-
def initialize(account_id, phone)
-
@account_id = account_id
-
@phone = phone
-
end
-
-
def account
-
return @account if defined?(@account)
-
@account = AccountBlock::Account.find_by(:id => @account_id)
-
end
-
-
private
-
-
def validate_phone
-
return if AccountBlock::PhoneValidation.new(@phone).valid?
-
errors.add :new_phone_number, 'is not valid'
-
end
-
-
def validate_account_type
-
return unless account
-
return unless invalid_account_types.include?(account.type)
-
errors.add :authentication, 'field cannot be edited'
-
end
-
-
def invalid_account_types
-
['AccountBlock::SmsAccount', 'SmsAccount']
-
end
-
end
-
end
-
1
module BxBlockProfile
-
1
class UpdateAccountValidator
-
1
include ActiveModel::Validations
-
-
ATTRIBUTES = [
-
1
[:first_name],
-
[:last_name],
-
[:new_phone_number, :full_phone_number],
-
[:new_password, :password],
-
[:new_email, :email],
-
]
-
-
1
attr_accessor(*ATTRIBUTES.map(&:first))
-
1
attr_accessor :current_password
-
-
1
validates :account, :presence => {:message => 'not found'}
-
1
validates :first_name, :presence => {:allow_nil => true}
-
1
validates :last_name, :presence => {:allow_nil => true}
-
1
validate :validate_phone_number
-
1
validate :validate_email
-
1
validate :validate_password
-
-
1
def initialize(account_id, params)
-
@account_id = account_id
-
-
@current_password = params[:current_password]
-
-
params.keys.each do |key|
-
self.send "#{key}=", params[key]
-
end
-
end
-
-
1
def account
-
return @account if defined?(@account)
-
@account = AccountBlock::Account.find_by(:id => @account_id)
-
end
-
-
1
def attributes
-
return {} unless valid?
-
-
attrs = {}
-
-
ATTRIBUTES.each do |values|
-
source = values.first
-
dest = values.last
-
-
value = send(source)
-
attrs[dest] = value if value
-
end
-
-
attrs
-
end
-
-
1
private
-
-
1
def validate_phone_number
-
return unless new_phone_number
-
validator = ChangePhoneValidator.new(@account_id, new_phone_number)
-
validate_with_validator validator
-
end
-
-
1
def validate_password
-
return if !current_password && !new_password
-
-
validator = ChangePasswordValidator
-
.new(@account_id, current_password, new_password)
-
validate_with_validator validator
-
end
-
-
1
def validate_email
-
return unless new_email
-
validator = ChangeEmailValidator.new(@account_id, new_email)
-
validate_with_validator validator
-
end
-
-
1
def validate_with_validator(validator)
-
return if validator.valid?
-
-
validator.errors.each do |attr, message|
-
errors.add attr, message
-
end
-
end
-
end
-
end
-
module BxBlockPushNotifications
-
class Provider
-
ONE_SIGNAL = :one_signal.freeze
-
-
SUPPORTED = [ONE_SIGNAL].freeze
-
-
class << self
-
def send_push_notification(title:, message:, user_ids:, app_url:)
-
provider_klass = case provider_name
-
when ONE_SIGNAL
-
Providers::OneSignal
-
else
-
raise unsupported_message(provider_name)
-
end
-
-
provider_klass.send_push_notification(
-
title: title, message: message, user_ids: user_ids, app_url: app_url
-
)
-
end
-
-
def provider_name
-
Rails.configuration.x.push_notifications.provider
-
end
-
-
def unsupported_message(provider)
-
supported_prov_msg = "Supported: #{SUPPORTED.join(", ")}."
-
if provider
-
"Unsupported Push Notifications provider: #{provider}. #{supported_prov_msg}"
-
else
-
"You must specify a Push Notifications provider. #{supported_prov_msg}"
-
end
-
end
-
end
-
end
-
end
-
require 'net/http'
-
-
module BxBlockPushNotifications
-
module Providers
-
class OneSignal
-
API_URL = "https://onesignal.com/api/v1/notifications"
-
-
class << self
-
def send_push_notification(title:, message:, user_ids:, app_url:)
-
uri = URI.parse(API_URL)
-
-
http = Net::HTTP.new(uri.host, uri.port)
-
-
http.use_ssl = true
-
request = Net::HTTP::Post.new(
-
uri.path,
-
'Content-Type' => 'application/json;charset=utf-8',
-
'Authorization' => "Basic #{auth_token}"
-
)
-
request.body = body(
-
title: title, message: message, user_ids: user_ids, app_url: app_url
-
).to_json
-
response = http.request(request)
-
JSON.parse(response.read_body)
-
end
-
-
private
-
-
def body(title:, message:, user_ids:, app_url:)
-
{
-
'app_id' => application_id,
-
'contents' => {'en' => message},
-
'headings' => {'en' => title },
-
'app_url' => app_url,
-
'include_player_ids' => user_ids
-
}
-
end
-
-
def application_id
-
Rails.configuration.x.push_notifications.application_id
-
end
-
-
def auth_token
-
Rails.configuration.x.push_notifications.auth_token
-
end
-
end
-
end
-
end
-
end
-
module BxBlockPushNotifications
-
class SendPushNotification
-
attr_reader :title, :message, :user_ids, :app_url
-
-
def initialize(title:, message:, user_ids:, app_url: nil)
-
@title = title
-
@message = message
-
@user_ids = user_ids
-
@app_url = app_url
-
end
-
-
def call
-
Provider.send_push_notification(
-
title: title, message: message, user_ids: user_ids, app_url: app_url
-
)
-
end
-
end
-
end
-
module BxBlockReviews
-
class Create
-
def initialize(current_user, review_attributes)
-
@current_user = current_user
-
@review_attributes = review_attributes
-
end
-
-
def execute
-
@review_attributes['reviewer_id'] = @current_user.id
-
review = Review.new(@review_attributes)
-
review.save
-
review
-
end
-
end
-
end
-
module BxBlockReviews
-
class Update
-
def initialize(review, review_attributes)
-
@review = review
-
@review_attributes = review_attributes
-
end
-
-
def execute
-
@review.assign_attributes(@review_attributes)
-
@review.save
-
@review
-
end
-
end
-
end
-
1
module BxBlockSms
-
1
class Provider
-
1
TWILIO = :twilio.freeze
-
1
KARIX = :karix.freeze
-
1
TEST = :test.freeze
-
-
1
SUPPORTED = [TWILIO, KARIX, TEST].freeze
-
-
1
class << self
-
1
def send_sms(to, text_content)
-
6
provider_klass = case provider_name
-
when TWILIO
-
Providers::Twilio
-
when KARIX
-
Providers::Karix
-
when TEST
-
Providers::Test
-
when 'text_local'
-
6
BxBlockSms::Providers::TextLocal
-
else
-
raise unsupported_message(provider_name)
-
end
-
-
6
provider_klass.send_sms(to, text_content)
-
end
-
-
1
def provider_name
-
6
Rails.configuration.x.sms.provider || 'text_local'
-
end
-
-
1
def unsupported_message(provider)
-
supported_prov_msg = "Supported: #{SUPPORTED.join(", ")}."
-
if provider
-
"Unsupported SMS provider: #{provider}. #{supported_prov_msg}"
-
else
-
"You must specify a SMS provider. #{supported_prov_msg}"
-
end
-
end
-
end
-
end
-
end
-
require "uri"
-
require "net/http"
-
-
module BxBlockSms
-
module Providers
-
class Karix
-
class << self
-
def send_sms(full_phone_number, text_content)
-
send_karix_api(full_phone_number, text_content)
-
end
-
-
private
-
-
def send_karix_api(full_phone_number, text_content)
-
url = URI(karix_message_url)
-
https = Net::HTTP.new(url.host, url.port);
-
https.use_ssl = true
-
request = Net::HTTP::Post.new(url)
-
request["Authorization"] = authorization
-
request_data = get_request_data(full_phone_number, text_content)
-
request["Content-Type"] = "application/json"
-
request.body = request_data.to_json
-
response = https.request(request)
-
puts response.read_body
-
end
-
-
def authorization
-
ActionController::HttpAuthentication::Basic.encode_credentials(
-
Rails.configuration.x.sms.account_id,
-
Rails.configuration.x.sms.auth_token
-
)
-
end
-
-
def get_request_data(full_phone_number, text_content)
-
{
-
"channel" => "sms",
-
"source" => karix_source,
-
"destination" => [full_phone_number],
-
"content" => {
-
"text" => text_content,
-
}
-
}
-
end
-
-
def karix_message_url
-
'https://api.karix.io/message/'
-
end
-
-
def karix_source
-
Rails.configuration.x.sms.from
-
end
-
end
-
end
-
end
-
end
-
module BxBlockSms
-
module Providers
-
class Test
-
class << self
-
def messages
-
@messages ||= []
-
end
-
-
def clear_messages
-
@messages = []
-
end
-
-
def send_sms(full_phone_number, text_content)
-
messages << {
-
from: Rails.configuration.x.sms.from,
-
to: full_phone_number,
-
content: text_content
-
}
-
end
-
end
-
end
-
end
-
end
-
1
require "rubygems"
-
1
require "net/https"
-
1
require "uri"
-
1
require "json"
-
-
1
module BxBlockSms
-
1
module Providers
-
1
class TextLocal
-
1
class << self
-
1
def send_sms(full_phone_number, text_content)
-
6
send_text_local_api(full_phone_number, text_content)
-
end
-
-
1
private
-
-
1
def send_text_local_api(full_phone_number, text_content)
-
6
uri = URI.parse(textlocal_message_url)
-
6
http = Net::HTTP.start(uri.host, uri.port)
-
6
request = Net::HTTP::Get.new(uri.request_uri)
-
-
6
res = Net::HTTP.post_form(uri, 'apikey' => ENV["TEXT_LOCAL_API"], 'message' => text_content, 'sender' => 'WTBOOK', 'numbers' => full_phone_number)
-
6
response = JSON.parse(res.body)
-
end
-
-
1
def textlocal_message_url
-
6
'https://api.textlocal.in/send/'
-
end
-
end
-
end
-
end
-
end
-
module BxBlockSms
-
module Providers
-
class Twilio
-
class << self
-
def send_sms(full_phone_number, text_content)
-
client = ::Twilio::REST::Client.new(account_id, auth_token)
-
client.messages.create({
-
from: from,
-
to: full_phone_number,
-
body: text_content
-
})
-
end
-
-
def account_id
-
Rails.configuration.x.sms.account_id
-
end
-
-
def auth_token
-
Rails.configuration.x.sms.auth_token
-
end
-
-
def from
-
Rails.configuration.x.sms.from
-
end
-
end
-
end
-
end
-
end
-
1
module BxBlockSms
-
1
class SendSms
-
1
attr_reader :to, :text_content
-
-
1
def initialize(to, text_content)
-
6
@to = to
-
6
@text_content = text_content
-
end
-
-
1
def call
-
6
Provider.send_sms(to, text_content)
-
end
-
end
-
end
-
1
class AudioUploader < CarrierWave::Uploader::Base
-
# Include RMagick or MiniMagick support:
-
# include CarrierWave::RMagick
-
# include CarrierWave::MiniMagick
-
-
# Choose what kind of storage to use for this uploader:
-
# storage :fog
-
-
# Override the directory where uploaded files will be stored.
-
# This is a sensible default for uploaders that are meant to be mounted:
-
1
def store_dir
-
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
-
end
-
-
# Provide a default URL as a default if there hasn't been a file uploaded:
-
# def default_url(*args)
-
# # For Rails 3.1+ asset pipeline compatibility:
-
# # ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_'))
-
#
-
# "/images/fallback/" + [version_name, "default.png"].compact.join('_')
-
# end
-
-
# Process files as they are uploaded:
-
# process scale: [200, 300]
-
#
-
# def scale(width, height)
-
# # do something
-
# end
-
-
# Create different versions of your uploaded files:
-
# version :thumb do
-
# process resize_to_fit: [50, 50]
-
# end
-
-
# Add an allowlist of extensions which are allowed to be uploaded.
-
# For images you might use something like this:
-
1
def extension_allowlist
-
%w(mp3 flp wav aif mid)
-
end
-
-
# Override the filename of the uploaded files:
-
# Avoid using model.id or version_name here, see uploader/store.rb for details.
-
# def filename
-
# "something.jpg" if original_filename
-
# end
-
end
-
1
class ImageUploader < CarrierWave::Uploader::Base
-
# Include RMagick or MiniMagick support:
-
# include CarrierWave::RMagick
-
1
include CarrierWave::MiniMagick
-
-
# Choose what kind of storage to use for this uploader:
-
-
# storage :fog
-
-
# Override the directory where uploaded files will be stored.
-
# This is a sensible default for uploaders that are meant to be mounted:
-
1
def store_dir
-
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
-
end
-
-
# Provide a default URL as a default if there hasn't been a file uploaded:
-
# def default_url(*args)
-
# # For Rails 3.1+ asset pipeline compatibility:
-
# # ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_'))
-
#
-
# "/images/fallback/" + [version_name, "default.png"].compact.join('_')
-
# end
-
-
# Process files as they are uploaded:
-
# process scale: [200, 300]
-
#
-
# def scale(width, height)
-
# # do something
-
# end
-
-
# Create different versions of your uploaded files:
-
# version :thumb do
-
# process resize_to_fit: [50, 50]
-
# end
-
-
# Add an allowlist of extensions which are allowed to be uploaded.
-
# For images you might use something like this:
-
1
def extension_allowlist
-
%w(jpg jpeg gif png)
-
end
-
-
# Override the filename of the uploaded files:
-
# Avoid using model.id or version_name here, see uploader/store.rb for details.
-
# def filename
-
# "something.jpg" if original_filename
-
# end
-
end
-
1
class PdfUploader < CarrierWave::Uploader::Base
-
# Include RMagick or MiniMagick support:
-
# include CarrierWave::RMagick
-
# include CarrierWave::MiniMagick
-
-
# Choose what kind of storage to use for this uploader:
-
# storage :fog
-
-
# Override the directory where uploaded files will be stored.
-
# This is a sensible default for uploaders that are meant to be mounted:
-
1
def store_dir
-
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
-
end
-
-
# Provide a default URL as a default if there hasn't been a file uploaded:
-
# def default_url(*args)
-
# # For Rails 3.1+ asset pipeline compatibility:
-
# # ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_'))
-
#
-
# "/images/fallback/" + [version_name, "default.png"].compact.join('_')
-
# end
-
-
# Process files as they are uploaded:
-
# process scale: [200, 300]
-
#
-
# def scale(width, height)
-
# # do something
-
# end
-
-
# Create different versions of your uploaded files:
-
# version :thumb do
-
# process resize_to_fit: [50, 50]
-
# end
-
-
# Add an allowlist of extensions which are allowed to be uploaded.
-
# For images you might use something like this:
-
1
def extension_allowlist
-
%w(pdf doc docx dot txt rtf csv ods xlsx pptx ppt)
-
end
-
-
# Override the filename of the uploaded files:
-
# Avoid using model.id or version_name here, see uploader/store.rb for details.
-
# def filename
-
# "something.jpg" if original_filename
-
# end
-
end
-
1
class VideoUploader < CarrierWave::Uploader::Base
-
1
require 'streamio-ffmpeg'
-
# Include RMagick or MiniMagick support:
-
# include CarrierWave::RMagick
-
# include CarrierWave::MiniMagick
-
-
# Choose what kind of storage to use for this uploader:
-
# storage :fog
-
-
# Override the directory where uploaded files will be stored.
-
# This is a sensible default for uploaders that are meant to be mounted:
-
1
def store_dir
-
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
-
end
-
-
# Provide a default URL as a default if there hasn't been a file uploaded:
-
# def default_url(*args)
-
# # For Rails 3.1+ asset pipeline compatibility:
-
# # ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_'))
-
#
-
# "/images/fallback/" + [version_name, "default.png"].compact.join('_')
-
# end
-
-
# Process files as they are uploaded:
-
# process scale: [200, 300]
-
#
-
# def scale(width, height)
-
# # do something
-
# end
-
-
# Create different versions of your uploaded files:
-
# version :thumb do
-
# process resize_to_fit: [50, 50]
-
# end
-
-
# Add an allowlist of extensions which are allowed to be uploaded.
-
# For images you might use something like this:
-
1
def extension_allowlist
-
%w(webm mpg mp2 mpeg mpe mpv ogg mp4 m4p m4v avi wmv mov qt flv swf avcdhd mp3)
-
end
-
-
# Override the filename of the uploaded files:
-
# Avoid using model.id or version_name here, see uploader/store.rb for details.
-
# def filename
-
# "something.jpg" if original_filename
-
# end
-
end
-
1
require 'active_model'
-
-
1
module BxBlockPosts
-
1
class BlobValidator < ActiveModel::EachValidator
-
1
def validate_each(record, attribute, values)
-
1
return unless values.attached?
-
-
Array(values).each do |value|
-
if options[:size_range].present?
-
if options[:size_range].min > value.blob.byte_size
-
record.errors.add(
-
attribute,
-
:min_size_error,
-
min_size: min_size_range
-
)
-
elsif options[:size_range].max < value.blob.byte_size
-
record.errors.add(
-
attribute,
-
:max_size_error,
-
max_size: max_size_range
-
)
-
end
-
end
-
-
unless valid_content_type?(value.blob)
-
record.errors.add(attribute, :content_type)
-
end
-
end
-
end
-
-
1
private
-
-
1
def min_size_range
-
ActiveSupport::NumberHelper.number_to_human_size(
-
options[:size_range].min
-
)
-
end
-
-
1
def max_size_range
-
ActiveSupport::NumberHelper.number_to_human_size(
-
options[:size_range].max
-
)
-
end
-
-
1
def valid_content_type?(blob)
-
return true if options[:content_type].nil?
-
-
case options[:content_type]
-
when Regexp
-
options[:content_type].match?(blob.content_type)
-
when Array
-
options[:content_type].include?(blob.content_type)
-
when Symbol
-
blob.public_send("#{options[:content_type]}?")
-
else
-
options[:content_type] == blob.content_type
-
end
-
end
-
end
-
end
-
module BxBlockAppointmentManagement
-
#Create slot for 6 days in advance
-
class AddOneDayAvailabilityWorker
-
include Sidekiq::Worker
-
-
def perform availability_id
-
availability_for_id(availability_id)
-
slot_for_today = BxBlockAppointmentManagement::Availability.find_by(
-
service_provider_id: @availability.service_provider_id,
-
availability_date: Date.today.strftime('%d/%m/%y')
-
).present?
-
unless !@availability.present? and slot_for_today
-
value = @availability.dup
-
value.availability_date = date.strftime('%y/%m/%d')
-
value.save!
-
trriger_job
-
end
-
end
-
-
def trriger_job
-
BxBlockAppointmentManagement::AddOneDayAvailabilityWorker.perform_at(
-
1.days.from_now, @availability.id
-
)
-
end
-
-
def availability_for_id id
-
@availability = BxBlockAppointmentManagement::Availability.find(id)
-
end
-
end
-
end
-
module BxBlockAppointmentManagement
-
#Create slot for 6 days in advance
-
class CreateAvailabilityWorker
-
include Sidekiq::Worker
-
-
def perform availability_id
-
availability_for_id(availability_id)
-
if @availability.present?
-
build_slots
-
trriger_job
-
end
-
end
-
-
def trriger_job
-
BxBlockAppointmentManagement::AddOneDayAvailabilityWorker.perform_at(
-
7.days.from_now, @availability.id
-
)
-
end
-
-
def availability_for_id id
-
@availability = BxBlockAppointmentManagement::Availability.find(id)
-
end
-
-
def build_slots
-
date = Date.strptime(@availability.availability_date, "%d/%m/%y") + 1.days
-
final_value = Array.new
-
6.times do
-
value = @availability.dup
-
value.availability_date = date.strftime('%y/%m/%d')
-
value.save
-
date = date + 1.days
-
end
-
end
-
-
end
-
end
-
require "mini_magick"
-
module BxBlockOrderManagement
-
class AttachCompressedImagesWorker
-
include Sidekiq::Worker
-
-
def perform(book_id)
-
book = BxBlockBook::Book.find_by(id: book_id)
-
if book && book.images.attached?
-
book.compressed_images.destroy_all
-
book.images.each do |image|
-
mini_image = MiniMagick::Image.open(image)
-
dim = mini_image.dimensions.map{|d| d/10}
-
mini_image.resize "#{dim.first}x#{dim.last}"
-
file = File.binread(mini_image.tempfile)
-
book.compressed_images.attach io: StringIO.open(file), filename: image.try(:blob).try(:filename).to_s, content_type: mini_image.mime_type
-
book.compressed_images.last.update(width: image.width, height: image.height, index: image.index)
-
end
-
end
-
end
-
-
end
-
end
-
1
module BxBlockOrderManagement
-
1
class SendDraftOrderMailWorker
-
1
include Sidekiq::Worker
-
-
1
def perform(order_id)
-
order = BxBlockOrderManagement::Order.find_by(id: order_id)
-
account = order.account
-
if order.draft?
-
DraftMailer.draft_email(order).deliver!
-
end
-
end
-
-
end
-
end